struts2支持三种验证方式

前言

  struts2支持三种验证方式:
     1.使用Annotations验证
     2.基于XML配置的验证
     3.手动验证

  本文主要简介第一种校验方式,使用的struts版本为:struts-2.2.1.1

正文

一 一个简单的例子

SimpleAnnotationAction.java:

复制代码
  
  
package com.struts2.validation; import org.apache.struts2.interceptor.validation.SkipValidation; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; import com.opensymphony.xwork2.validator.annotations.Validations; import com.opensymphony.xwork2.validator.annotations.ValidatorType; @Validations(requiredStrings = { @RequiredStringValidator(fieldName = " userName " ,message = " 用户名不能为空! " ), @RequiredStringValidator(fieldName = " userName " ,message = " 密码不能为空! " ) } ) public class SimpleAnnotationAction extends ActionSupport { private String userName; private String password; @Override @Validations(requiredFields = { @RequiredFieldValidator(type = ValidatorType.SIMPLE,fieldName = " userName " ,message = " 用户名不能为null!! " ) } ) public String execute() throws Exception { return super .execute(); } /* 运行: http://localhost :8080/struts2/validation/simpleAnnotationLogin.action 结果: 用户名不能为空! 密码不能为空! 用户名不能为null!! 密码不能为null!! */ @Validations(requiredFields = { @RequiredFieldValidator(type = ValidatorType.SIMPLE,fieldName = " password " ,message = " 密码不能为null!! " ) } ) public String login(){ return " success " ; } /* 运行: http://localhost :8080/struts2/validation/simpleAnnotationLogin2.action 结果: 用户名不能为空! 密码不能为空! 用户名不能为null!! 密码不能为null!! */ public String login2(){ return " success " ; } /* 运行: http://localhost :8080/struts2/validation/simpleAnnotationLogin2.action 结果:页面发生跳转 */ @SkipValidation public String login3(){ return " success " ; } /* 运行: http://localhost :8080/struts2/validation/simpleAnnotationLogin2.action 结果:页面发生跳转 */ public String login5(){ return " success " ; } public String getUserName() { return userName;} public void setUserName(String userName) { this .userName = userName;} public String getPassword() { return password;} public void setPassword(String password) { this .password = password;} }
复制代码

 struts.xml

复制代码
  
  
< package name ="validation" namespace ="/validation" extends ="struts-default" > < action name ="simpleAnnotationLogin" class ="com.struts2.validation.SimpleAnnotationAction" method ="login" > < result name ="input" > /SimpleAnnotation.jsp </ result > < result name ="success" type ="redirect" > /LoginSuccess.jsp </ result > </ action > < action name ="simpleAnnotationLogin2" class ="com.struts2.validation.SimpleAnnotationAction" method ="login2" > < result name ="input" > /SimpleAnnotation.jsp </ result > < result name ="success" type ="redirect" > /LoginSuccess.jsp </ result > </ action > < action name ="simpleAnnotationLogin3" class ="com.struts2.validation.SimpleAnnotationAction" method ="login3" > < result name ="input" > /SimpleAnnotation.jsp </ result > < result name ="success" type ="redirect" > /LoginSuccess.jsp </ result > </ action > < action name ="simpleAnnotationLogin5" class ="com.struts2.validation.SimpleAnnotationAction" method ="login5" > < interceptor-ref name ="validation" > < param name ="validateAnnotatedMethodOnly" > true </ param > </ interceptor-ref > < result name ="input" > /SimpleAnnotation.jsp </ result > < result name ="success" type ="redirect" > /LoginSuccess.jsp </ result > </ action > </ package >
复制代码

SimpleAnnotation.jsp

复制代码
  
  
<% @ page language = " java " import = " java.util.* " pageEncoding = " utf-8 " %> <% @ taglib prefix = " s " uri = " /struts-tags " %> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > < html > < head > </ head > < body > < s:fielderror ></ s:fielderror > < form action ="../validation/manualValidation.action" method ="post" > < input type ="text" name ="userName" /> < br > < input type ="password" name ="password" /> < br > < input type ="submit" value ="提交" /> </ form > </ body > </ html >
复制代码

LoginSuccess.jsp

复制代码
  
  
<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %> <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > </ head > < body > < h1 > 登录成功!! </ h1 > </ body > </ html >
复制代码

结论
   1.Action类中使用Validations Annotation定义验证。
   2.Action中,可以在方法上、类上定义验证Annotations,所有的验证器都将同时作用在映射为Action的方法上。
   3.Action中有多个方法被映射为Action时,类上和方法上所有定义的验证Annotations都将作用在每个映射为Action的方法上。
   4.Action中校验失败时,返回input逻辑视图
   5.可以使用@SkipValidation跳过所有的验证检查,包括自身方法定义的校验器。
   6.可以在Action映射中使用如下代码跳过校验检查
     <interceptor-ref name="validation">
         <param name="validateAnnotatedMethodOnly">true</param>
     </interceptor-ref>

  二  校验器使用说明

1.Validations Annotation的使用
 Validations中定义了一些验证器的数组,用于存放验证规则,定义如下
 public @interface Validations {
 //自定义校验器数组
    public CustomValidator[] customValidators() default {};
    //字段转换错误校验器数组
    public ConversionErrorFieldValidator[] conversionErrorFields() default {};
    //日期范围校验器
    public DateRangeFieldValidator[] dateRangeFields() default {};
 //Email校验器
    public EmailValidator[] emails() default {};
 //字段表达式校验器
    public FieldExpressionValidator[] fieldExpressions() default {};
 //整数范围校验器
    public IntRangeFieldValidator[] intRangeFields() default {};
 //必填字段校验器
    public RequiredFieldValidator[] requiredFields() default {};
 //必填字符串校验器
    public RequiredStringValidator[] requiredStrings() default {};
 //字符串长度校验器
    public StringLengthFieldValidator[] stringLengthFields() default {};
 //URL校验器
    public UrlValidator[] urls() default {};
    //带条件的Vistor校验器
    public ConditionalVisitorFieldValidator[] conditionalVisitorFields() default {};
 //Vistor校验器
    public VisitorFieldValidator[] visitorFields() default {};
 //正则表达式校验器
    public RegexFieldValidator[] regexFields() default {};
 //表达式校验器
    public ExpressionValidator[] expressions() default {};
}

2.@RequiredStringValidator —— 必填字符串校验器
 校验要求:指定字段不能为null且字符串长度大于0
 参数: fieldName:校验字段名
    trim:校验时取出字符串两边的空格,默认为true
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
3.RequiredFieldValidator —— 必填校验器
 校验要求:指定字段不能为null
 参数: fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息

4.IntRangeFieldValidator —— 整数范围校验器
 校验要求:int、long、short字段的整数值在指定的范围内
 参数:min:指定最小值,可选,没有则不检查最小值
    max:指定最大值,可选,没有则不检查最大值
    fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
5.DateRangeFieldValidator —— 日期范围校验器
 校验要求:日期在指定的范围内  
 参数:min:指定最小值,可选,没有则不检查最小值
    max:指定最大值,可选,没有则不检查最大值 
    fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
      
6.EmailValidator —— Email地址校验器
 校验要求:指定的字段为Email地址
 参数: fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
7.ExpressionValidator —— 表达式校验器
 校验要求:指定的ONGL表达式返回true。
 参数: expression:ONGL表达式  
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
      
8.UrlValidator —— URL校验器
 校验要求:校验指定的字段值是否为合法的URL
 参数: fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
9.StringLengthFieldValidator —— 字符串长度校验器
 校验要求:字符串长度在指定的范围内
 参数:minLength:指定最小长度,可选,没有则不检查最小长度
    maxLength:指定最大长度,可选,没有则不检查最大长度 
    trim:校验时取出字符串两边的空格,默认为true
    fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
    
10.ConversionErrorFieldValidator —— 转换错误校验器
 校验要求:校验指定字段是否发生类型转换错误
 参数: fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
11.VisitorFieldValidator —— Vistor校验器
 说明:普通校验器只能校验基本数据类型和字符串类型,该校验器可以校验对象里面的属性。
 参数:context:用于校验的context
    appendPrefix: 校验发生错误时是否在错误信息中添加前最消息
    fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
12. RegexFieldValidator —— 正则表达式校验器
 校验要求:指定字段匹配指定的正则表达式
 参数:expression:正则表达式
    fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
13.ConditionalVisitorFieldValidator —— 带条件的Vistor校验器
 验证要求:在条件不满足时,和Vistor校验器功能一样,条件满足则不执行Vistor校验
 参数: fieldName:校验字段名
    message:校验失败时的消息
    key:校验失败时返回i18n中指定名称的消息
   
14.CustomValidator —— 自定义校验器 
 校验器:自定义校验器 

三 各种校验器使用

AnnotationValidationAction.java

复制代码
  
  
package com.struts2.validation; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.validator.annotations.ConditionalVisitorFieldValidator; import com.opensymphony.xwork2.validator.annotations.ConversionErrorFieldValidator; import com.opensymphony.xwork2.validator.annotations.CustomValidator; import com.opensymphony.xwork2.validator.annotations.DateRangeFieldValidator; import com.opensymphony.xwork2.validator.annotations.EmailValidator; import com.opensymphony.xwork2.validator.annotations.ExpressionValidator; import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator; import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator; import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator; import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator; import com.opensymphony.xwork2.validator.annotations.UrlValidator; import com.opensymphony.xwork2.validator.annotations.Validations; import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator; public class AnnotationValidationAction extends ActionSupport{ private Name name; private String password; private String email; private int age; private Date birthday; private String homeUrl; private String question; private String answer; @Validations( stringLengthFields = {@StringLengthFieldValidator(fieldName = " password " ,minLength = " 8 " ,maxLength = " 20 " ,message = " 密码的长度必须大于8小于20个字符 " )}, emails = {@EmailValidator(fieldName = " email " ,message = " 邮件字段的格式不对 " )}, conversionErrorFields = {@ConversionErrorFieldValidator(fieldName = " age " ,message = " 年龄输入的值转换错误 " )}, intRangeFields = {@IntRangeFieldValidator(fieldName = " age " ,min = " 0 " ,max = " 150 " ,message = " 年龄范围为0到150 " )}, urls = {@UrlValidator(fieldName = " homeUrl " ,message = " 个人主页的格式不对 " )}, dateRangeFields = {@DateRangeFieldValidator(fieldName = " birthday " ,min = " 1900-01-01 " ,message = " 日期输入不真确 " )}, visitorFields = {@VisitorFieldValidator(fieldName = " name " ,context = " name " ,message = " 姓名错误: " ,appendPrefix = true )}, fieldExpressions = {@FieldExpressionValidator(expression = " age>10 " ,fieldName = " age " ,message = " 年龄不大于10岁 " )}, expressions = {@ExpressionValidator(expression = " age<10 " ,message = " 年龄大于10岁 " )}, // 不显示信息 regexFields = {@RegexFieldValidator(expression = " 1* " ,fieldName = " question " ,message = " 问题不是全部1 " )}, conditionalVisitorFields = {@ConditionalVisitorFieldValidator(expression = " age>10 " ,context = " name " ,fieldName = " name " ,appendPrefix = true ,message = " ConditionVistor: " )} ) public String execute() throws Exception { return super .execute(); } public Name getName() { return name; } public void setName(Name name) { this .name = name; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } public String getEmail() { return email; } public void setEmail(String email) { this .email = email; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this .birthday = birthday; } public String getHomeUrl() { return homeUrl; } public void setHomeUrl(String homeUrl) { this .homeUrl = homeUrl; } public String getQuestion() { return question; } public void setQuestion(String question) { this .question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this .answer = answer; } }
复制代码

Name.java

复制代码
  
  
package com.struts2.validation; import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; import com.opensymphony.xwork2.validator.annotations.Validations; @Validations(requiredFields = {@RequiredFieldValidator(fieldName = " lastName " ,message = " LastName错误 " )}) public class Name { private String firstName; private String lastName; public String getFirstName() { return firstName; } @Validations(requiredStrings = {@RequiredStringValidator(fieldName = " firstName " ,message = " FirstName错误 " )}) public void setFirstName(String firstName) { this .firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this .lastName = lastName; } }
复制代码

create.jsp

复制代码
  
  
<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %> <% @ taglib prefix = " s " uri = " /struts-tags " %> <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > </ head > < body > < s:fielderror ></ s:fielderror > < s:form action ="../validation/annotationValidation.action" > < s:textfield label ="FirstName" name ="name.firstName" ></ s:textfield > < s:textfield label ="LastName" name ="name.lastName" ></ s:textfield > < s:textfield label ="密 码:" name ="password" ></ s:textfield > < s:textfield label ="Email:" name ="email" ></ s:textfield > < s:textfield label ="年龄:" name ="age" ></ s:textfield > < s:textfield label ="出生日期:" name ="birthday" ></ s:textfield > < s:textfield label ="个人主页:" name ="homeUrl" ></ s:textfield > < s:textfield label ="问题:" name ="question" ></ s:textfield > < s:textfield label ="答案:" name ="answer" ></ s:textfield > < s:submit ></ s:submit > </ s:form > </ body > </ html >
复制代码

struts.xml

复制代码
 
 
<? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" > < struts > < package name ="validation" namespace ="/validation" extends ="struts-default" > < action name ="annotationValidation" class ="com.struts2.validation.AnnotationValidationAction" > < result name ="input" > /validation/create.jsp </ result > < result name ="success" > /FirstApplication/LoginSuccess.jsp </ result > </ action > </ package > </ struts >

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值