How to disable struts 2 validation before form sub

2019-09-03 10:48发布

问题:

I'm doing a project with struts2, Hibernate.

I want struts to validate my form. I have added a MyAction-validation.xml and it works fairly well. (I say fairly well because it doesn't validate on the client side. I have set the validate attribute of the <s:form/> tag to true)

First it provided me some errors and googling it I got that I should add a result with input name. So now I have a result with input name in my action without understanding well how it works and why.

My action returns a plain form when it is called by myAction.action url and when the form is submitted the data goes directly to the action parameters and saved in database. Then a filled form will be shown with a success message. The form fields should be validated upon the submission. But they are validated whenever the action is invoked. I tried @SkipValidation annotation but it cancels the validation completely. Even when I call the validate method in the execute method it doesn't run. I tested it by some System.out.println lines. My action definition in the struts.xml is the following:

<action name="ShowAddItemPage" class="action.clerk.ShowAddItemPage">
  <result name="success" type="tiles">addItem</result>
  <result name="generalError" type="tiles">clerkGeneralError</result>
  <result name="input" type="tiles">addItem</result>
</action>
  1. How can I make the validation work on the client side?
  2. How can I make the validation run only upon the form submission and disable it when there form fields are provided by the application?
  3. What is input result name for and why did I have to add it to the action results?

回答1:

  1. By setting the validate attribute to true, just like you said.
  2. By having a different action for displaying the form, or by creatong an interceptor that skips validation on a GET (that's what I used to do), etc.
  3. "input" is the result used when validation fails, although you can change it. If validation fails (and by default, type conversion failures as well) it has to go somewhere, and the "input" result is where.