I have a form that I need to be validated when submitted. I have added public void validate()
to my action class. However, the errors are displayed even in the initial page load when the form was not yet submitted.
I have read this and this, but nothing solved my problem. Is it really that hard to implement such simple things as skipping validation on first form load? :(
I am using manual validation inside action class.
struts.xml
<action name="login" class="community.action.LoginAction">
<result name="success" type="redirect">/forums/list</result>
<result name="login">/WEB-INF/login.jsp</result>
<result name="input">/WEB-INF/login.jsp</result>
</action>
LoginAction.java
public void validate() {
//validation rule
addActionError("Error message");
}
public String execute() {
if (//username and password correct) {
return SUCCESS; //redirect to forums page
} else {
return LOGIN;
}
}
Currently the errors display even if form is not submitted.
I tried to use the @SkipValidation
annotation over execute()
, but this prevents errors from being shown at all, even after form submission.
You need to use different action names. One for viewing the form and other for submitting.
You can have one more method in the LoginAction class to return the login.jsp for the Input with @SkipValidation
LoginAction.java
public String execute()
{
if (//username and password correct) {
return SUCCESS; //redirect to forums page
} else {
return LOGIN;
}
}
public void validate()
{
//validation rule
addActionError("Error message");
}
@SkipValidation
public String loginForm()
{
return INPUT;
}
Now the validation will occur only on execute method. First the request should come to loginForm method.To make this,slight modification in the configuration
struts.xml
<action name="login_*" class="community.action.LoginAction" method="{1}">
<result name="success" type="redirect">/forums/list</result>
<result name="login">/WEB-INF/login.jsp</result>
<result name="input">/WEB-INF/login.jsp</result> </action>
Here method="{1}" entry in the action element will be used to check which method got requested for, if nothing is specified in the request then the execute() method will be invoked otherwise mentioned method will be invoked.Note the action name has changed to login_*
To mention the method name in the JSP:
-------
<s:submit name="SubmitButton" value="Click To Login" action="login_loginForm"/>
In the submit UI element above action have got mentioned as login_loginForm. Here login_ refers the action name and loginForm refers the method to be invoked. Hope this will help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With