Validation and Theme in Struts 2
I am working on a Struts 2 project, the problem is that I use <constant name="struts.ui.theme" value="simple"/> in my struts.xml to layout my JSP page (for example, placing 2-3 text files in one line using table code) in accordance with the applied CSS, but I cannot show a validation error on the same jsp page due to theme="simple" .
Configuration:
<struts> <!-- Configuration for the default package. --> <constant name="struts.ui.theme" value="simple"/> <package name="default" extends="struts-default"> <action name="validateUser" class="login.LoginAction"> <result name="SUCCESS">/welcome.jsp</result> <result name="input">/login.jsp</result> </action> </package> </struts> Act:
public class LoginAction extends ActionSupport{ private String username; // getter and setter private String password; // getter and setter @Override public String execute() { // some business logic here.... return "SUCCESS"; } //simple validation @Override public void validate(){ if("".equals(getUsername())){ addFieldError("username", getText("username.required")); } if("".equals(getPassword())){ addFieldError("password", getText("password.required")); } } } View:
<s:form action="validateUser" validate="true" > <table> <tr> <td>username</td> <td><s:textfield label="username" name="username" /><td/> </tr> <tr> <td>password</td> <td><s:password label="password" name="password" /><td/> <tr> <td> <s:submit label="submit" name="submit"/></td> </tr> </table> </s:form> Is there a way to save the layout with my CSS, and also use the Struts 2 validation?
Of course! An XHTML theme will automatically add a fieldError tag to your input tags;
when using a simple theme, instead you need to add them manually and give an identifier to your tags to match them (unless it is auto-generated and more difficult to determine):
<td> <s:textfield id="username" label="username" name="username" /> <s:fielderror fieldName="username" /> </td> <td> <s:password id="password" label="password" name="password" /> <s:fielderror fieldName="password" /> </td> PS: I think they are in typos, and the errors are in the question only, not in the real code, but you have:
- self-closing
<td/>, - unclosed
<tr>and - a
<tr>with one<td>without a pointercolspan="2".