Você está na página 1de 7

Strut2 Validation Framework With Example

In Struts 2, the validation framework is well engineered. The Struts 2 takes validation component to a new level of refinement, modularity, and clean integration. Before looking in to code examples first we will look in to the validation framework architecture to see how it fits into the workflow of Struts2. The validation framework architecture: There are three main components at play in the validation framework: the domain data, validation metadata, and the validators. Each plays a important role in the work of validation. Domain data : are JavaBean properties on a Struts 2 action: username, password, and age. These properties are assumed to hold the data our action will work with when it begins execution Validation metadata : A middle component lies between the validators and the data properties themselves. This middle component is the metadata that associates individual data properties with the validators that should be used to verify the correctness of the values in those properties at runtime. We can associate as many validators with each property. We can map data properties to validators with XML files or with Java annotation Validators: The core validation is done by validators. A validator is a reusable component that contains the logic for performing some fine-grained act of validation. The framework comes with a rich set of built-in validators, and we can even write our own. To have our data validated by these validators, we simply wire up your properties to the desired validators via some XML or Java annotations. When the validation executes, each property is validated by the set of validators with which its been associated by the metadata layer. Now lets look at validation framework in the Struts 2 workflow: The basic validation and the validation framework uses the ValidationAware interface to store errors and the workflow interceptor to route back to the input page if error occurs in the validation logic. The basic validation examples and validation framework examples all work in the context of the defaultStack of interceptors that come with Struts 2. The following sequence of interceptors from the defaultStack, as defined in struts-default.xml: <interceptor-ref name="params"/> <interceptor-ref name="conversionError"/> <interceptor-ref name="validation"/> <interceptor-ref name="workflow"/> As you can see defaultStack, the params interceptor and the conversionError interceptor both fire before we get to the validation-related interceptors. These two interceptors finish up the work of transferring the data from the request and converting it to the correct Java types of the target properties. If conversion error occurs then an error would be added to the ValidationAware methods. Validation interceptor is the entry in to

the validation framework. When this interceptor fires, it conducts all the validation thats been defined via the validation metadata. If validation error occurs then an error would be added to the ValidationAware methods. Whether errors are added or not, we still proceed to the next interceptor, the workflow interceptor. Workflow interceptor has two phases one is to invoke the validate() method which is entry point to basic validation and second phase of the workflow interceptors is checking the errors, it does this by invoking ValidationAware's hasErrors(0 method. We can use basic validation methods and the validation framework both at the same time. Due to the clean lines of Struts 2, everything except the actual validation logic itself is shared between the two methods. When we use the defaultStack, both the validation and workflow interceptors fire every time. This means that you could use both forms of validation at the same time. First, the validation interceptor runs all validations that we define with the validation framework metadata. Then, when the workflow interceptor runs, it still checks to see if our action implements the validate() method. Even if we have already run some validators via the validation interceptor, we can still provide some additional validation code in a validate() method. When the second phase of the workflow interceptor checks for errors, it doesnt care or know who created them. The effect is the same The validation framework is that the validation code is contained in reusable validators.. Struts 2 provides built-in validators . Just we have to wire the validators to our properties. If some validation logic that isnt handled by the built-in validators we have two choices. first if we found that validation logic is something reusable in the future then we can implement our own custom validator, otherwise we can use the second option that is putting our validation logic in the validate method. Lets rewrite the Register action which is written in the basic validation article to use the validation framework instead of the validate() method. We replace the programmatic validations of the validate() method with some metadata that creates associations between our data properties and the validators that contain the desired logic. We Declaring our validation metadata with ActionClass-validations.xml. The naming convention of the XML validation metadata file is ActionClass-validations.xml. This file is then placed in the package directory structure next to the action class itself. In our example, Register actions validation metadata file, Register-validation.xml. There are two types of validators you can declare: field and nonfield. Filed Validators Field validators are validators that operate on an individual field. <validators> <field name="bar"> <field-validator type="required"> <message>You must enter a value for bar.</message> </field-validator> </field> </validators>

NonField Validators This validators apply to the whole action and often contain checks that involve more than one of the field values. The built-in validators only offer one instance of a nonfield validator: the expression validator. This useful validator allows we to embed an OGNL expression that contains the logic of the validation we wish to perform. Let us add validation logic to the small application Registering a new user to the website. Here in this article we will create an Action class which contains domain data or fields. package xch.com.struts2; import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport{ private String name; private Integer age; Domain data(Field Data) private String email; private String telephone; private String password; public String addUser() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }

public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } } Now we will add entry for this new action class in STRUTS.XML file. Open the struts.xml file which will be present under resources folder. And add following content between <package></package> tag. <action name="register" class="net.viralpatel.struts2.RegisterAction">

<!--on success user will be redirected to SuccessCustomer.jsp page.--> <result name="success"> SuccessRegistration.jsp</result> <!-- Notice that there is another result tag with name input. Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input--> <result name="input">RegistrationForm.jsp</result> </action> Now we will create JSP pages for RegistrationForm and success page. Registrionform.jsp <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Registration Form - Struts2 Demo </title> </head> <body> <h2>Registration Form</h2>

<s:form action="register.action" method="post"> <s:textfield name="username" key="name" size="20" /> <s:password key="password" />

<s:textfield name="age" key="age" size="20" /> <s:textfield name="email" key="email" size="20" /> <s:textfield name="telephone" key="telephone" size="20" /> <s:submit method="addUser" key="label.add.user" align="center" /> </s:form> </body> </html> SuccessRegistration.jsp <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Registration of User Page - Struts2 Demo </title> </head> <body> <h2>User Registered Successfully.</h2> </body> </html> Now open the ApplicationResources.properties file from /resources folder and add following key/values in it. username= UserName password=Password age= Age email= Email telephone= Telephone label.add.user=Add Customer errors.invalid=${getText(fieldName)} is invalid. errors.required=${getText(fieldName)} is required.

errors.number=${getText(fieldName)} must be a number. errors.range=${getText(fieldName)} is not in the range ${min} and ${max}. Now we can add validation logic to the Registration form. Following are the validations rules added to the Registration form. UserName field is mandatory Password field is mandatory username and password field should not be same. Age field is mandatory. It should be a number between 1 and 120. Email field is mandatory. It should be a valid email address. Telephone is mandatory

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "HTTP://WWW.OPENSYMPHONY.COM/XWORK/XWORK-VALIDATOR-1.0.2.DTD"> <validators> <field name="name"> <field-validator type="stringlength"> <param name="maxLength">8</param> <param name="minLength">5</param> <message>While ${username} is a nice name, a valid username must be between ${minLength} and ${maxLength} characters long. </message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <message>You must enter a value for password.</message> </field-validator> </field> <field name="age"> <field-validator type="required"> <message key="errors.required" /> </field-validator> <field-validator type="int"> <param name="min">1</param> <param name="max">100</param> <message key="errors.range"/> </field-validator> </field>

<field name="email"> <field-validator type="requiredstring"> <message key="errors.required" /> </field-validator> <field-validator type="email"> <message key="errors.invalid" /> </field-validator> </field> <field name="telephone"> <field-validator type="requiredstring"> <message key="errors.required" /> </field-validator> </field> <validator type="expression"> <param name="expression">username != password</param> <message>Username and password can't be the same.</message> </validator> </validators> It is very easy to add Client Side validation or JavaScript validation to any form in Struts2. All you have to do is to add VALIDATE=TRUE in form tag in your JSP file. For example open RegistrationForm.jsp and add validate=true in form tag. Struts2 automatically generates the JavaScript code for client side validation of form.

Você também pode gostar