I am trying to validate a form using the Struts2 validations annotation but it does not seem to work and does not show required mark on the labels. Here is my code:
login.jsp
:
<s:form action="/Login" validate = "true">
<table>
<tr>
<td><s:label theme=”simple” required="true">Username :</s:label></td>
<td><s:textfield name="userName" theme=”simple” /></td>
</tr>
<tr>
<td><s:label theme=”simple” required="true">Password :</s:label></td>
<td><s:textfield name="password" theme=”simple” /></td>
</tr>
<tr>
<td><s:submit value="Login" /></td>
</tr>
</table>
</s:form>
LoginAction.java
:
public class LoginAction extends ActionSupport {
private String userName;
private String password;
@Validations(requiredStrings={@RequiredStringValidator(type=ValidatorType.FIELD, message="User Name can ot be empty.", fieldName="userName")})
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Validations(requiredStrings={@RequiredStringValidator(type=ValidatorType.FIELD, message="Password can ot be empty.", fieldName="password" )})
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute()
{
return SUCCESS;
}
}
struts.xml
:
<struts>
<package name="demo" extends="struts-default">
<action name="*" class="mypkg.action.{0}Action">
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
Can somebody help and notice if there is something wrong with my code?
If you use Validations
annotation then you should place it on action method. Validator annotations are placed on the setter methods. Also you are using validate = "true"
which means the client-side validation. Make sure you have javascript (with the help of <s:head/>
) and themes like xhtml
or css_xhtml
applyed to the form to make the validation errors visible. I.e. theme simple
doesn't work here, remove it from fields.
If you don’t specify a theme, then Struts 2 will use the xhtml theme by default.
Referrences: