Struts data validation

Source: Internet
Author: User

Validation of form data:

Front desk verification: mainly through the JS verification, the expression of data is legitimate!

Background verification: Through the background Java code to verify!

Struts also provides a way to data validation!

Struts data is tested and completed by interceptors:

<interceptor name= "Validation" class= " Org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor "/>

Code to validate all methods in the action:

Steps:

1. Build a Struts environment

2. login.jsp

3.useraction.java

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Package Com.gqx.validate;import Java.util.date;public class User {private string Username;private string pwd;private String Email;private Date birth;public string GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String getpwd () {return pwd;} public void SetPwd (String pwd) {this.pwd = pwd;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public Date Getbirth () {return birth;} public void Setbirth (Date birth) {This.birth = birth;} @Overridepublic String toString () {return "User [birth=" + Birth + ", email=" + email + ", pwd=" + pwd+ ", username=" + US Ername + "]";}}

Useraction.java

Package Com.gqx.validate;import com.opensymphony.xwork2.actionsupport;/** * Note: If you want to use the data validation feature of Struts, Must inherit actionsupport or implement related interfaces * @author gqxing * */public class Useraction extends actionsupport{//package data private User user=new Us ER ();p ublic void setUser (user user) {this.user = user;} Public User GetUser () {return user;} @Overridepublic void Validate () {//user name non-empty if (user.getusername () = = NULL | | ". Equals (User.getusername ())) {//Save error message Super.addfielderror (" UserName "," username must be filled in! ") ");} Password if (user.getpwd () = = NULL | | ". Equals (User.getpwd ())) {Super.addfielderror (" pwd "," Password Required ");}} Business method Public String Register () {System.out.println (user); return SUCCESS;} List display (without data validation) public String list () {return SUCCESS;}}

You can also validate a specified method, such as validating only the Register method, and not validating the list method

Package Com.gqx.validate;import com.opensymphony.xwork2.actionsupport;/** * Note: If you want to use the data validation feature of Struts, Must inherit actionsupport or implement related interfaces * @author gqxing * */public class Useraction extends actionsupport{//package data private User user=new Us ER ();p ublic void setUser (user user) {this.user = user;} Public User GetUser () {return user;} public void Validateregister () {//user name non-empty if (user.getusername () = = NULL | | ". Equals (User.getusername ())) {//Save error message Super.addfielderror (" UserName "," username must be filled in! ") ");} Password if (user.getpwd () = = NULL | | ". Equals (User.getpwd ())) {Super.addfielderror (" pwd "," Password Required ");}} Business method Public String Register () {System.out.println (user); return SUCCESS;} List display (without data validation) public String list () {return SUCCESS;}}

XML validates all the methods in the action:

Tedious, design a lot of repetitive verification logic! For example: non-null validation, numeric validation, email, date, and so on.

Struts is encapsulated for common validation, which provides a validator that validates the specified common business logic!

All validators provided by

Struts -Path: xwork-core-2.3.4.1.jar/ Com.opensymphony.xwork2.validator.validators/default.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE validators Public "-//apache struts//xwork Validator Definition 1.0//en" "http://struts.apache.org/d Tds/xwork-validator-definition-1.0.dtd "><!--START Snippet:validators-default--><validators> < Validator Name= "Required" class= "Com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> < Validator name= "requiredstring" class= "Com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/    > <validator name= "int" class= "Com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> <validator name= "Long" class= "Com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/> < Validator Name= "Short" class= "Com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/> < Validator Name= "Double" class= "Com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> < Validator name= "Date" class= "Com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator "/> <validator name=" expression "class= "Com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> <validator name= "Fieldexpression" class= "Com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> <validator name= "Email" class= "Com.opensymphony.xwork2.validator.validators.EmailValidator"/> <validator name= "url" class= " Com.opensymphony.xwork2.validator.validators.URLValidator "/> <validator name=" Visitor "class=" Com.opensymphony.xwork2.validator.validators.VisitorFieldValidator "/> <validator name=" Conversion "class=" Com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator "/> <validator name=" Stringlength "class=" Com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator "/> <validator Name= "regex" class= "Com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> <validator name= "cOnditionalvisitor "class=" Com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator "/> </validators><!--END Snippet:validators-default--

If you write XML, you define validation rules:

1) XML file name syntax: Actionclassname-validation.xml

Note: This XML needs to be in the same directory as the action to be validated in the current period:

Example: Useraction-validation.xml

2) Write XML

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE validators Public "-//apache struts//xwork Validator 1.0.3//en" "http://struts.apache.org/dtds/ Xwork-validator-1.0.3.dtd "><validators><!--Verify email--><field name=" User.email ">< Field-validator type= "email" ><message> Email format Error! </message></field-validator></field>< each field!--validated is represented by field--><field name= " User.username "><!--specified validator--><field-validator type=" requiredstring "><!--validation failed error message-- <message> user name cannot be empty! </message></field-validator></field><!--verify pwd--><field name= "user.pwd" ><!--non-null- -><field-validator type= "requiredstring" ><message> password cannot be empty! </message></field-validator><!--length--><field-validator type= "Stringlength" ><param name = "MinLength" >6</param><param name= "maxLength" >8</param><message> password must be 6-8 bit! </message></field-validator></field><!--Validation Date--><field name= "User.birth" ><field-validator type= "date" ><message> date format is incorrect!    </message></field-validator></field></validators>

XML validates the method specified in the action:

Similar to the XML validation method above: Verify that the contents of the XML file are unchanged;

File name:

Syntax: Actionclassname-actionname-validation.xml

Example: Useraction-user_register-validation.xml

Verifying the Register method in Useraction

Validation summary

Code:

Override Validate () To verify action all methods

Validate method Name (), validates the method that specifies the method name

Xml:

Verify all methods: Actionclassname-validation.xml

To verify the specified method: Actionclassname-actionname-validation.xml

Code validation,

More flexible, can meet all the needs.

More cumbersome, to write repetitive verification and judgment logic!

Fit: Less form fields are used!

XML Validation:

Generic, but not flexible enough to validate a specific simple business.

Fit: Verify more form fields, can greatly simplify the code!

(Too many configuration files)

Struts data validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.