Struts 2 skips checking when loading the first page

I have a form that needs to be confirmed upon submission. I added public void validate() to my action class. However, errors are displayed even on the initial page load, when the form has not yet been submitted.

I read this and this , but nothing solved my problem. Is it really so difficult to implement such simple things as skipping the check for loading the first form ?: (

I use manual validation inside an 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; } } 

Errors are currently displayed even if the form is not submitted.

I tried using the @SkipValidation annotation over execute() , but this prevents the display of errors at all, even after the form is @SkipValidation .

+4
source share
3 answers

You may have another method in the LoginAction class to return login.jsp for login 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 check will be performed only when the method is executed. First, the request should come to the loginForm method. To do this, a small configuration modification

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 the method = "{1}" in the action element will be used to check which request was requested, if nothing is specified in the request, then the execute () method will be called, otherwise the mentioned method will be called. Note that the action name has changed to login _ *

To specify a method name in JSP:


  ------- <s:submit name="SubmitButton" value="Click To Login" action="login_loginForm"/> 


In the view item of the view item above, the action is referred to as login_loginForm. Here login_ stands for the name of the action and loginForm refers to the method to be called. Hope this helps

+6
source

You need to use different action names. One to view the form and the other to submit.

+2
source

This means that I already called the action while loading the first page. The easiest way to fix this is to rename your action from login to loginAction or something else.

+1
source

Source: https://habr.com/ru/post/1441756/


All Articles