Struts2 Validatation - struts2

I have used Struts2 in a period time, but I am still very confused with Struts2 Validation.
I have used xml-validation, or method addFieldError() to validate, but when I first come to input form-page, a page with struts-tags, and a <s:form>, I can not just go to this page by a href-link, I must go through another action, I read that page jsp with struts-tags must come from a action.
And I usually create a Action just for redirect to this input page, in execute() method just "success" and the role of this action is to go to input page legally, and in action which process the input form input-page, I choose the "input" result is still this input page.
So, I feel uncomfortable to do this, I always have a GoToSiteAction, just first-time go to input page.
So, I really need your help!!.

Use the with input fields , create a action and create a validation xml file with same name as java file name
For example : AddInput.java
xml file: AddInput-validation.xml
put it in same package.
write all the validations you need for the form in xml file like this.
<field name="U_Id">
<field-validator type="requiredstring" short-circuit="true">
<message>Affiliate Id cannot be empty</message>
</field-validator>
</field>
<field name="Password">
<field-validator type="requiredstring" short-circuit="true">
<message>Password cannot be empty</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">30</param>
<message>Password cannot be less than 5 or more than 30</message>
</field-validator>
</field>
When you hit the action it will first hit the validation xml and check for the validation then process the action class part.

You are not using or not using the struts2-conventions plugin to it's full effect. Please see: http://struts.apache.org/2.1.6/docs/convention-plugin.html search this page for the string "Examples of Action and Result to Template mapping" and consider the table which follows.
In the future after adding the struts2-conventions-plugin jar to your project add the postfix "-input" to the end of all future forms.
Say we created a form to add a new employee:
/WEB-INF/content/add-employee-input.jsp
The struts2 form tag would reference an action simply called "add-employee" in a java class probably named something like com.mypackages.struts2.AddEmployee then if the add-employee action validation fails then "input" is returned and the "add-employee-input" form is again rendered. However we do not need to create a "add-employee-input" action, the conventions plugin will do this for us automatically... as such we can directly enter the form if we wish by referencing it and this is very convenient.
Try it out and you'll see what I mean.

Related

how to implement global redirect page in struts2

We're using Struts 2 in our web application. There are bunch of action mappings defined already, I want to implement a feature where any Urls starting with /buy and not mapped to any of the existing action mappings e.g. /buy/new or buy/old should be redirected to buy/index action. For example if someone is trying to go to /buy/bla1 or /buy/bla2 or buy/bla1/bla2/bla3 should go to buy/index.
Define the following action in your /buy package:
<action name="*">
<result type="redirectAction">index</result>
</action>
Alternatively you can just use:
<default-action-ref name="index" />
But then you will get no redirect. Instead the index page will show under the nonexisting address.
You also need to set the following parameter in your struts.properties:
struts.action.extension = action,,
You can add other extensions to the parameter, but as far as i know there is no wildcard for all extensions. The blank string covers directories like /buy/bla but /buy/bla.x won't be covered and will produce a 404 error unless you add x to the list of extensions.
If this is not good enough you might be better off solving this by using redirect rules in the webserver.
You can use default action reference and provide a JSP success path to it.
If any unmatched action is received then it will call the given action and forward it to the result JSP page.

How to disable struts 2 validation before form submission?

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>
How can I make the validation work on the client side?
How can I make the validation run only upon the form submission and disable it when there form fields are provided by the application?
What is input result name for and why did I have to add it to the action results?
By setting the validate attribute to true, just like you said.
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.
"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.

Struts2 and form validation of prefilled forms

I'm using the validate() - method of struts2 to validate the form input. In my struts.xml I can define a result with name "input" which is displayed if the validation fails. This for the context :-)
Now my question: the form I want to validate contains a selectbox which is filled out of a database. The first time the form is displayed everything works fine. But if I validate the form and the "input" - result is displayed, I get an IOException because of the iterator which outputs the db-result into my selectbox. Is there a solution from struts2 or do I have to use a plugin or something like that? Thank you!
When validation fails, it's often necessary to "reload" data for the form page. There's a FAQ entry that covers repopulating controls after validation, mainly detailing the Preparable interface (preferred) and the use of the <s:action> tag (there are some subtle gotchas that can pop up with this, but in general, it's also okay).

how to display validation message in specific <div> element in Struts2

I'm new to Struts 2 and facing this problem in keeping the layout of my page:
<s:form action="abc.action"><br>
<s:textfield key="name" label="Name" /><%--here I need to display errormessage for `name`--%>
<br>
<s:textfield key="email" label="Email" /><%--here I need to display errormessage for `email`--%>
<br>
<s:submit>
</s:form>
I'm using xml-validator for my action class, this works fine. but the validation-error messages appear over the fieldname and text-box. but i want it to come afterwards respective text-box (inside another html-container). Kindly advise.
If you're used to writing HTML, switch to the simple theme.
In struts.xml is probably the best place:
<struts>
<constant name="struts.ui.theme" value="simple" />
</struts>
Then just use the fielderror tag to put the error for the field where you want it.
It's a good to be familiar with the Struts2 tags: http://struts.apache.org/release/2.3.x/docs/tag-reference.html
That is the default according to Struts2 default templating. To change it, see http://www.mkyong.com/struts2/working-with-struts-2-theme-template/
You Can also Use Struts2 validation Framework
Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic by implementing java interface.
com.opensymphony.xwork2.Validator
Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path
com/opensymphony/xwork2/validator/validators/default.xml
Validators Scope
There are two types of Validators in Struts2 Validation Framework.
Field Validators
Non-field validators
Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.
<validators>
<field name="bar">
<field-validator type="required">
<message>You must enter a value for bar.</message>
</field-validator>
</field>
</validators>
Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.
<validators>
<validator type="expression">
<param name="expression">foo lt bar</param>
<message>Foo must be greater than Bar.</message>
</validator>
</validators>
For whole detail example visit this link link to struts2 validation

struts2 conditional xml validation

I have what I'd think is a common issue but an entire day of googling hasn't turned up anything useful.
I have a form with a checkbox and a textfield. I'd like to do a regex validation of the textfield, but only if the checkbox is selected. Regex validation is currently working for other non-conditional fields but I can't for the life of me figure out if there is a syntax that allows for this in the action-validation.xml file. ie. I have something like below for other fields. What I need is a way of making this conditionaly evaluated only if the checkbox is selected.
<validators>
<field name="sn">
<field-validator type="regex" >
<param name="expression">
[0-9]{12}
</param>
<message>Serial number format is invalid. Please try again</message>
</field-validator>
</field>
</validators>
Does anyone have a code example of how to do this?
Any help is much appreciated.
For Struts 1 there was a validation rule called "validwhen" that you could use to perform complex validations, but for Struts 2, as far as I know there is no such validation.
For Struts 2 you could go with the Expression Validator in which you can specify an OGNL expression to use, so I guess you could try something like this:
<validator type="expression">
<param name="expression">checkboxField eq "selected" and inputText eq "bla"</param>
<message>....</message>
</validator>
One thing I don't know is if there is a easy way of doing your regular expression check using OGNL (you'll have to look into it).
Additionally, if that does not work, you can always write your own custom validator.
The expression and fieldexpression validators take an OGNL expression. Evaluating to true passes false fails. You can use them quite easily for this requirement.
Personally I would just use the built in validators via XML like you're doing and then implement any custom validation logic in the validate() method (or methodname-validate() method). Just preference, no good reason really.

Resources