1. Struts2中的输入校验
2. 编码方式校验
1) Action一定要继承自ActionSupport
2) 针对某个要进行校验的请求处理方法编写一个 public void validateXxx()方法,在方法内部进行表单数据校验.
3) 也可针对所有的请求处理方法编写public void validate()方法。
4) 在校验方法中,可以通过addFieldError()方法来添加字段校验错误消息。
5) 当校验失败时,Struts框架会自动跳转到name为input的Result页面。在校验失败页面中,可以使用<s:fielderror/>来显示错误消息
6) 简单,灵活。但重用性不高。
3. XML配置方式校验。在编码方式之前被执行。
1) 针对要校验的Action类,在同包下编写一个名为:Action类名-validation.xml校验规则文件。
2) 在校验规则文件中添加校验规则:具体的校验器名,参数可参看Struts2的reference或Struts2的API。
a) Field校验:针对Action类中每个非自定义类型的Field进行校验的规则。
<field name="要校验的Field名">
<field-validator type="校验规则器名" short-circuit="是否要短路径校验(默认是false)">
<param name="校验器要使用的参数名">值</param>
<message>校验失败时的提示消息</message>
</field-validator>
<!-- 还可添加其它的校验规则 -->
</field>
b) 非Field校验:针对Action类的某些Field使用OGNL表达进行组合校验。
<validator type="fieldexpression">
<param name="fieldName">pwd</param>
<param name="fieldName">pwd2</param>
<param name="expression"><![CDATA[pwd==pwd2]]></param><!-- OGNL表达式 -->
<message>确认密码和密码输入不一致</message>
</validator>
c) visitor校验:主要是用来校验Action类中的自定义类型Field。(针对使用模型驱动方式时)
i) 在Action类的的校验规则文件中针对自定义类型Field使用visitor校验规则。
<!-- 针对自定义Field使用visitor校验 -->
<field name="user">
<field-validator type="required" short-circuit="true">
<message>用户的信息必填</message><!-- 消息前缀 -->
</field-validator>
<field-validator type="visitor"><!-- 指定为visitor校验规则 -->
<param name="context">userContext</param><!-- 指定本visitor校验的上下文名 -->
<param name="appendPrefix">true</param><!-- 是否要添加校验失败消息的前缀 -->
<message>用户的</message><!-- 消息前缀 -->
</field-validator>
</field>
ii) 针对visitor的Field编写一个校验规则文件.文件名为: visitor字段类型名[-visitor校验的上下文名]-validation.xml. 例如: 本例中的文件名为User-userContext-validation.xml
注意: 此文件要存放到visitor字段类型所在的包下.
iii) 在visitor的Field校验规则文件中针对要校验的Field添加校验规则.
3) 在校验失败页面(名为input的result页面)中,可以使用<s:fielderror/>来显示错误消息。
4) 默认情况下,XML的校验规则对Action中所有的请求处理方法生效.此时应该只针对每个要校验的请求处理方法指定校验。有两种方式:
i) 只为Action中的指定方法指定校验规则文件,配置文件命名为:Action类型名-别名-validation.xml,
别名是要校验的方法对应的Action标签的name属性值。
如:UserAction在struts2.xml的配置为:
<package name="my" extends="struts-default" namespace="/">
<action name="user_*" class="com.javacrazyer.web.action.UserAction" method="{1}">
<result name="success">/info.jsp</result>
<result name="input">/user_{1}.jsp</result>
</action>
</package>
● UserAction中有registe方法和login方法,要对registe方法进行校验,则它的校验规则文件名为:UserAction-user_registe-validation.xml。
● 如果使用visitor校验器,必需指定visitor校验的上下文名。
ii) 在校验拦截器中指定要验证的方法。不太实用。
<action name="user_*" class="com.javacrazyer.web.action.UserAction" method="{1}">
<result name="success">/info.jsp</result>
<result name="input">/user_{1}.jsp</result>
<interceptor-ref name="defaultStack">
<!-- 给校验拦截器指定不进行校验的方法列表:用逗号隔开 -->
<param name="validation.excludeMethods">*</param>
<!-- 给校验拦截器指定要进行校验的方法列表:用逗号隔开 -->
<param name="validation.includeMethods">regist</param>
</interceptor-ref>
</action>
5) 同时使用客户端校验和服务器端校验
i) 设置<s:form>标签的validate属性:
false:默认值。校验框架只执行服务器端校验。
true:先执行客户端校验,然后再执行服务器端校验。
form标签会根据你在服务器端配置的验证规则生成对应的JavaScript验证代码。
目前支持的内置校验器:required、requiredstring、stringlength、regex validator、email、url、int、double
ii) 不太好用,不建议使用。建议使用jQuery进行页面表单校验。
6) 自定义校验器:
i) 继承自FieldValidatorSupport抽象类。重写validate(Object obj)方法
ii) 注册校验器类. 在应用程序的classpath下新建一校验器注册文件。名为validators.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="校验器名" class="校验器类的全限定名"/>
</validators>
4. Annotation方式校验: Struts2提供了注解的方式校验
1) @Validation 指明这个类或者接口将使用基于注解的校验。Struts2.1中已被标识为过时。
2) @Validations() 在同一个方法上要使用多个注解校验时。
3) @SkipValidation 指定某个方法不需要校验。否则所有方法都会使用校验。也可以在检验拦截器中使用validateAnnotatedMethodOnly
4) 13个内置校验器的注解版本:(注:这些注解都只能用在方法级别上) 具体参数参见Struts2的API或Reference。
@RequiredFieldValidator
@RequiredStringValidator
@StringLengthFieldValidator
@IntRangeFieldValidator
@DoubleRangeFieldValidator
@DateRangeFieldValidator
@ExpressionValidator
@FieldExpressionValidator
@RegexFieldValidator
@EmailValidator
@UrlValidator
@VisitorFieldValidator
@ConversionErrorFieldValidator
第一个示例:XML配置式校验器---注册页面
acc_registe.jsp
- <span style="font-size: medium;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2中基于XML配置式的校验器使用示例</title>
- </head>
- <body>
- <h3>XML配置式校验器---注册页面</h3><hr/>
- <div style="color:red"><s:fielderror/></div>
- <form action="acc_registe.action" method="post">
- <table>
- <tr>
- <td>ID</td>
- <td><input type="text" name="id" value="${param.id}"/></td>
- </tr>
- <tr>
- <td>登录名</td>
- <td><input type="text" name="name" value="${param.name}"/></td>
- </tr>
- <tr>
- <td>密码</td>
- <td><input type="password" name="pwd"/></td>
- </tr>
- <tr>
- <td>重复密码</td>
- <td><input type="password" name="pwd2"/></td>
- </tr>
- <tr>
- <td>时间</td>
- <td><input type="text" name="registed_date" value="${param.registed_date}"/></td>
- </tr>
- <tr>
- <td>email</td>
- <td><input type="text" name="email" value="${param.email}"/></td>
- </tr>
- <tr>
- <td>考试成绩</td>
- <td><input type="text" name="score" value="${param.score}"/></td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value=" 提交 "/></td>
- </tr>
- </table>
- </form>
- </body>
- </html></span>
src/struts.xml
- <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
- <struts>
- <!-- 请求参数的编码方式 -->
- <constant name="struts.i18n.encoding" value="UTF-8"/>
- <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->
- <constant name="struts.action.extension" value="action,do,go,xkk"/>
- <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.configuration.xml.reload" value="true"/>
- <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.devMode" value="false"/>
- <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->
- <constant name="struts.serve.static.browserCache" value="false" />
- <!-- 是否允许在OGNL表达式中调用静态方法,默认值为false -->
- <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
- <!-- 指定由spring负责action对象的创建
- <constant name="struts.objectFactory" value="spring" />
- -->
- <!-- 是否开启动态方法调用 -->
- <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
- <package name="my" extends="struts-default" namespace="/">
- <action name="acc_*" class="com.javacrazyer.web.action.AccountAction" method="{1}">
- <result name="success">/info.jsp</result>
- <result name="input">/acc_{1}.jsp</result>
- </action>
- </package>
- </struts>
- </span>
AccountAction.java
- <span style="font-size: medium;">package com.javacrazyer.web.action;
- import java.util.Date;
- import com.opensymphony.xwork2.ActionSupport;
- public class AccountAction extends ActionSupport {
- private static final long serialVersionUID = -1418893621512812472L;
- private Integer id;
- private String name;
- private String pwd;
- private String pwd2;
- private Double score;
- private Date registed_date;
- private String email;
- public String registe() throws Exception{
- System.out.println("registe-------------------");
- return SUCCESS;
- }
- public String login()throws Exception{
- return SUCCESS;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Double getScore() {
- return score;
- }
- public void setScore(Double score) {
- this.score = score;
- }
- public Date getRegisted_date() {
- return registed_date;
- }
- public void setRegisted_date(Date registedDate) {
- registed_date = registedDate;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- public String getPwd2() {
- return pwd2;
- }
- public void setPwd2(String pwd2) {
- this.pwd2 = pwd2;
- }
- }</span>
AccountAction-validation.xml [与AccountAction同目录]
- <span style="font-size: medium;"><?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="id">
- <field-validator type="required" short-circuit="true">
- <message>ID必填的</message>
- </field-validator>
- <field-validator type="int">
- <param name="min">20</param>
- <param name="max">50</param>
- <message>ID必须在 ${min} 到 ${max} 之间</message>
- </field-validator>
- </field>
- <field name="name">
- <field-validator type="requiredstring" short-circuit="true">
- <message>姓名是必填的</message>
- </field-validator>
- <field-validator type="regex">
- <param name="expression"><![CDATA[(^[a-zA-Z_]\w{3,9}$)]]></param>
- <message>姓名不合法</message>
- </field-validator>
- </field>
- <field name="pwd">
- <field-validator type="requiredstring" short-circuit="true">
- <message>密码是必填的</message>
- </field-validator>
- </field>
- <!-- 非字段校验 -->
- <validator type="fieldexpression">
- <param name="fieldName">pwd</param>
- <param name="fieldName">pwd2</param>
- <param name="expression"><![CDATA[pwd==pwd2]]></param><!-- OGNL表达式 -->
- <message>确认密码和密码输入不一致</message>
- </validator>
- <field name="score">
- <field-validator type="double">
- <param name="minInclusive">0.0</param>
- <param name="maxInclusive">100.0</param>
- <message>成绩必须在${minInclusive}和${maxInclusive}之间</message>
- </field-validator>
- </field>
- <field name="email" >
- <field-validator type="regex">
- <param name="expression"><![CDATA[(^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-])+((\.com)|(\.cn)|(\.net)|(\.org)|(\.info)|(\.edu)|(\.mil)|(\.gov)|(\.biz)|(\.ws)|(\.us)|(\.tv)|(\.cc)|(\.aero)|(\.arpa)|(\.coop)|(\.int)|(\.jobs)|(\.museum)|(\.name)|(\.pro)|(\.travel)|(\.nato)|(\..{2,3})|(\..{2,3}\..{2,3}))$)]]></param>
- <message>邮箱不合法</message>
- </field-validator>
- </field>
- <field name="registed_date">
- <field-validator type="date">
- <param name="min">1970-01-01</param>
- <param name="max">2019-01-01</param>
- <message>注册日期不合法</message>
- </field-validator>
- </field>
- </validators></span>
第二个示例:XML配置式校验器---登录和注册页面
user_login.jsp
- <span style="font-size: medium;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2中基于XML配置式的校验器使用示例</title>
- </head>
- <body>
- <h3>XML配置式校验器---登录页面</h3><hr/>
- <div style="color:red"><s:fielderror/></div>
- <form action="user_login.action" method="post">
- <table>
- <tr>
- <td>登录名</td>
- <td><input type="text" name="user.name" value="${param['user.name']}"/></td>
- </tr>
- <tr>
- <td>密码</td>
- <td><input type="password" name="user.pwd"/></td>
- </tr>
- <tr><td colspan="2"><input type="submit" value=" 提交 "/></td></tr>
- </table>
- </form>
- </body>
- </html></span>
user_registe.jsp
- <span style="font-size: medium;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2中基于XML配置式的校验器使用示例</title>
- </head>
- <body>
- <h3>XML配置式校验器---注册页面</h3><hr/>
- <div style="color:red"><s:fielderror/></div>
- <form action="user_registe.action" method="post">
- <table>
- <tr>
- <td>ID</td>
- <td><input type="text" name="user.id" value="${param['user.id']}"/></td>
- </tr>
- <tr>
- <td>登录名</td>
- <td><input type="text" name="user.name" value="${param['user.name']}"/></td>
- </tr>
- <tr>
- <td>密码</td>
- <td><input type="password" name="user.pwd"/></td>
- </tr>
- <tr>
- <td>重复密码</td>
- <td><input type="password" name="user.pwd2"/></td>
- </tr>
- <tr>
- <td>时间</td>
- <td><input type="text" name="user.registed_date" value="${param['user.registed_date']}"/></td>
- </tr>
- <tr>
- <td>email</td>
- <td><input type="text" name="user.email" value="${param['user.email']}"/></td>
- </tr>
- <tr>
- <td>考试成绩</td>
- <td><input type="text" name="user.score" value="${param['user.score']}"/></td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value=" 提交 "/></td>
- </tr>
- </table>
- </form>
- </body>
- </html></span>
src/struts.xml
- <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
- <struts>
- <!-- 请求参数的编码方式 -->
- <constant name="struts.i18n.encoding" value="UTF-8"/>
- <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->
- <constant name="struts.action.extension" value="action,do,go,xkk"/>
- <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.configuration.xml.reload" value="true"/>
- <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.devMode" value="false"/>
- <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->
- <constant name="struts.serve.static.browserCache" value="false" />
- <!-- 是否允许在OGNL表达式中调用静态方法,默认值为false -->
- <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
- <!-- 指定由spring负责action对象的创建
- <constant name="struts.objectFactory" value="spring" />
- -->
- <!-- 是否开启动态方法调用 -->
- <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
- <package name="my" extends="struts-default" namespace="/">
- <action name="user_*" class="com.javacrazyer.web.action.UserAction" method="{1}">
- <result name="success">/info.jsp</result>
- <result name="input">/user_{1}.jsp</result>
- </action>
- </package>
- </struts>
- </span>
UserAction.java
- <span style="font-size: medium;">package com.javacrazyer.web.action;
- import com.javacrazyer.domain.User;
- import com.opensymphony.xwork2.ActionSupport;
- public class UserAction extends ActionSupport {
- private static final long serialVersionUID = -2554018432709689579L;
- private User user; //自定义类型Field
- public String registe() throws Exception{
- System.out.println("registe======================");
- return SUCCESS;
- }
- public String login() throws Exception{
- return SUCCESS;
- }
- /*
- public void validate(){
- System.out.println("调用validate方法");
- }
- //执行exceute方法前调用
- public void validateRegiste(){
- System.out.println("调用validateRegiste方法");
- String lname = user.getLoginname();
- if(null != lname && !lname.trim().matches("[a-zA-Z_]\\w{3,19}")){
- this.addFieldError("loginname", "用户名不能为空,且只能由4-20个字母和数字组成");
- //this.addActionError("用户名不能为空,且只能由4-20个字母和数字组成");
- }
- }
- public void validateLogin(){
- System.out.println("调用validateLogin方法");
- }
- */
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- }</span>
UserAction-user_login-validation.xml
- <span style="font-size: medium;"><?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使用visitor校验 -->
- <field name="user">
- <field-validator type="required" short-circuit="true">
- <message>用户的信息必填</message><!-- 消息前缀 -->
- </field-validator>
- <field-validator type="visitor">
- <param name="context">userLoginContext</param><!-- 指定本visitor校验的上下文 -->
- <param name="appendPrefix">true</param><!-- 是否要添加校验失败消息的前缀 -->
- <message>用户的</message><!-- 消息前缀 -->
- </field-validator>
- </field>
- </validators></span>
UserAction-user_registe-validation.xml
- <span style="font-size: medium;"><?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使用visitor校验 -->
- <field name="user">
- <field-validator type="required" short-circuit="true">
- <message>用户的信息必填</message><!-- 消息前缀 -->
- </field-validator>
- <field-validator type="visitor">
- <param name="context">userContext</param><!-- 指定本visitor校验的上下文 -->
- <param name="appendPrefix">true</param><!-- 是否要添加校验失败消息的前缀 -->
- <message>用户的</message><!-- 消息前缀 -->
- </field-validator>
- </field>
- </validators></span>
第三个示例:注解方式校验器---注册页面
acc2_registe.jsp
- <span style="font-size: medium;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2中基于Annotation配置式的校验器使用示例</title>
- </head>
- <body>
- <h3>Annotation配置式校验器---注册页面</h3><hr/>
- <div style="color:red"><s:fielderror/></div>
- <form action="acc2_registe.action" method="post">
- <table>
- <tr>
- <td>ID</td>
- <td><input type="text" name="id" value="${param.id}"/></td>
- </tr>
- <tr>
- <td>登录名</td>
- <td><input type="text" name="name" value="${param.name}"/></td>
- </tr>
- <tr>
- <td>密码</td>
- <td><input type="password" name="pwd"/></td>
- </tr>
- <tr>
- <td>重复密码</td>
- <td><input type="password" name="pwd2"/></td>
- </tr>
- <tr>
- <td>时间</td>
- <td><input type="text" name="registed_date" value="${param.registed_date}"/></td>
- </tr>
- <tr>
- <td>email</td>
- <td><input type="text" name="email" value="${param.email}"/></td>
- </tr>
- <tr>
- <td>考试成绩</td>
- <td><input type="text" name="score" value="${param.score}"/></td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value=" 提交 "/></td>
- </tr>
- </table>
- </form>
- </body>
- </html></span>
src/struts.xml
- <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
- <struts>
- <!-- 请求参数的编码方式 -->
- <constant name="struts.i18n.encoding" value="UTF-8"/>
- <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->
- <constant name="struts.action.extension" value="action,do,go,xkk"/>
- <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.configuration.xml.reload" value="true"/>
- <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.devMode" value="false"/>
- <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->
- <constant name="struts.serve.static.browserCache" value="false" />
- <!-- 是否允许在OGNL表达式中调用静态方法,默认值为false -->
- <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
- <!-- 指定由spring负责action对象的创建
- <constant name="struts.objectFactory" value="spring" />
- -->
- <!-- 是否开启动态方法调用 -->
- <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
- <package name="my" extends="struts-default" namespace="/">
- <action name="acc2_*" class="com.javacrazyer.web.action.Account2Action" method="{1}">
- <result name="success">/info.jsp</result>
- <result name="input">/acc2_{1}.jsp</result>
- </action>
- </package>
- </struts>
- </span>
Account2Action.java
- <span style="font-size: medium;">package com.javacrazyer.web.action;
- import java.util.Date;
- import org.apache.struts2.interceptor.validation.SkipValidation;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
- import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
- import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
- import com.opensymphony.xwork2.validator.annotations.Validations;
- import com.opensymphony.xwork2.validator.annotations.ValidatorType;
- /**
- * 使用注解来配置校验的示例
- *
- */
- public class Account2Action extends ActionSupport {
- private static final long serialVersionUID = -1418893621512812472L;
- private Integer id;
- private String name;
- private String pwd;
- private String pwd2;
- private Double score;
- private Date registed_date;
- private String email;
- @Validations(
- requiredStrings={@RequiredStringValidator(fieldName="name",message="我的用户名是必须的",shortCircuit=true,trim=true,type=ValidatorType.FIELD),
- @RequiredStringValidator(fieldName="pwd",message="我的密码是必须的",shortCircuit=true,trim=true,type=ValidatorType.FIELD)},
- fieldExpressions={@FieldExpressionValidator(fieldName="pwd", message="两次密码不相同",expression="pwd==pwd2")},
- regexFields={@RegexFieldValidator(expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-])+((\\.com)|(\\.cn)|(\\.net)|(\\.org)|(\\.info)|(\\.edu)|(\\.mil)|(\\.gov)|(\\.biz)|(\\.ws)|(\\.us)|(\\.tv)|(\\.cc)|(\\.aero)|(\\.arpa)|(\\.coop)|(\\.int)|(\\.jobs)|(\\.museum)|(\\.name)|(\\.pro)|(\\.travel)|(\\.nato)|(\\..{2,3})|(\\..{2,3}\\..{2,3}))$")}
- )
- public String registe() throws Exception{
- System.out.println("registe-------------------");
- return SUCCESS;
- }
- @SkipValidation
- public String login()throws Exception{
- return SUCCESS;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Double getScore() {
- return score;
- }
- public void setScore(Double score) {
- this.score = score;
- }
- public Date getRegisted_date() {
- return registed_date;
- }
- public void setRegisted_date(Date registedDate) {
- registed_date = registedDate;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- public String getPwd2() {
- return pwd2;
- }
- public void setPwd2(String pwd2) {
- this.pwd2 = pwd2;
- }
- }</span>
第四个示例:注解方式校验器---用户注册页面
user2_registe.jsp
- <span style="font-size: medium;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2中基于XML配置式的校验器使用示例</title>
- </head>
- <body>
- <h3>XML配置式校验器---注册页面</h3><hr/>
- <div style="color:red"><s:fielderror/></div>
- <form action="user2_registe.action" method="post">
- <table>
- <tr>
- <td>ID</td>
- <td><input type="text" name="user.id" value="${param['user.id']}"/></td>
- </tr>
- <tr>
- <td>登录名</td>
- <td><input type="text" name="user.name" value="${param['user.name']}"/></td>
- </tr>
- <tr>
- <td>密码</td>
- <td><input type="password" name="user.pwd"/></td>
- </tr>
- <tr>
- <td>重复密码</td>
- <td><input type="password" name="user.pwd2"/></td>
- </tr>
- <tr>
- <td>时间</td>
- <td><input type="text" name="user.registed_date" value="${param['user.registed_date']}"/></td>
- </tr>
- <tr>
- <td>email</td>
- <td><input type="text" name="user.email" value="${param['user.email']}"/></td>
- </tr>
- <tr>
- <td>考试成绩</td>
- <td><input type="text" name="user.score" value="${param['user.score']}"/></td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value=" 提交 "/></td>
- </tr>
- </table>
- </form>
- </body>
- </html></span>
src/struts.xml
- <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
- <struts>
- <!-- 请求参数的编码方式 -->
- <constant name="struts.i18n.encoding" value="UTF-8"/>
- <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->
- <constant name="struts.action.extension" value="action,do,go,xkk"/>
- <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.configuration.xml.reload" value="true"/>
- <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->
- <constant name="struts.devMode" value="false"/>
- <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->
- <constant name="struts.serve.static.browserCache" value="false" />
- <!-- 是否允许在OGNL表达式中调用静态方法,默认值为false -->
- <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
- <!-- 指定由spring负责action对象的创建
- <constant name="struts.objectFactory" value="spring" />
- -->
- <!-- 是否开启动态方法调用 -->
- <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
- <package name="my" extends="struts-default" namespace="/">
- <!-- 使用Annotation配置校验的Action -->
- <action name="user2_*" class="com.javacrazyer.web.action.User2Action" method="{1}">
- <result name="success">/info.jsp</result>
- <result name="input">/user2_{1}.jsp</result>
- </action>
- </package>
- </struts>
- </span>
User2Action.java
- <span style="font-size: medium;">package com.javacrazyer.web.action;
- import com.javacrazyer.domain.User;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
- import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
- import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
- import com.opensymphony.xwork2.validator.annotations.Validations;
- import com.opensymphony.xwork2.validator.annotations.ValidatorType;
- /**
- * 使用注解来配置校验器
- *
- */
- public class User2Action extends ActionSupport {
- private static final long serialVersionUID = -2554018432709689579L;
- private User user; //自定义类型Field
- @Validations(
- requiredStrings={@RequiredStringValidator(fieldName="user.name",message="你的用户名是必须的",shortCircuit=true,trim=true,type=ValidatorType.FIELD),
- @RequiredStringValidator(fieldName="user.pwd",message="人的密码是必须的",shortCircuit=true,trim=true,type=ValidatorType.FIELD)},
- fieldExpressions={@FieldExpressionValidator(fieldName="user.pwd", message="两次密码不相同",expression="user.pwd==user.pwd2")},
- regexFields={@RegexFieldValidator(fieldName="user.email",message="邮箱不合法",expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-])+((\\.com)|(\\.cn)|(\\.net)|(\\.org)|(\\.info)|(\\.edu)|(\\.mil)|(\\.gov)|(\\.biz)|(\\.ws)|(\\.us)|(\\.tv)|(\\.cc)|(\\.aero)|(\\.arpa)|(\\.coop)|(\\.int)|(\\.jobs)|(\\.museum)|(\\.name)|(\\.pro)|(\\.travel)|(\\.nato)|(\\..{2,3})|(\\..{2,3}\\..{2,3}))$")}
- )
- public String registe() throws Exception{
- System.out.println("registe======================");
- return SUCCESS;
- }
- public String login() throws Exception{
- return SUCCESS;
- }
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- }</span>
另附:
User.java
- <span style="font-size: medium;">package com.javacrazyer.domain;
- import java.util.Date;
- public class User {
- private Integer id;
- private String name;
- private String pwd;
- private String pwd2;
- private Double score;
- private Date registed_date;
- private String email;
- public User(){}
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- public String getPwd2() {
- return pwd2;
- }
- public void setPwd2(String pwd2) {
- this.pwd2 = pwd2;
- }
- public Double getScore() {
- return score;
- }
- public void setScore(Double score) {
- this.score = score;
- }
- public Date getRegisted_date() {
- return registed_date;
- }
- public void setRegisted_date(Date registedDate) {
- registed_date = registedDate;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- }</span>
与user.java同一目录的User-userContext-validation.xml
- <span style="font-size: medium;"><?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="id">
- <field-validator type="required" short-circuit="true">
- <message>ID必填的</message>
- </field-validator>
- <field-validator type="int">
- <param name="min">20</param>
- <param name="max">50</param>
- <message>ID必须在 ${min} 到 ${max} 之间</message>
- </field-validator>
- </field>
- <field name="name">
- <field-validator type="requiredstring" short-circuit="true">
- <message>姓名是必填的</message>
- </field-validator>
- <field-validator type="regex">
- <param name="expression"><![CDATA[(^[a-zA-Z_]\w{3,9}$)]]></param>
- <message>姓名不合法</message>
- </field-validator>
- </field>
- <field name="pwd">
- <field-validator type="requiredstring" short-circuit="true">
- <message>密码是必填的</message>
- </field-validator>
- </field>
- <!-- 非字段校验 -->
- <validator type="fieldexpression">
- <param name="fieldName">pwd</param>
- <param name="fieldName">pwd2</param>
- <param name="expression"><![CDATA[pwd==pwd2]]></param><!-- OGNL表达式 -->
- <message>确认密码和密码输入不一致</message>
- </validator>
- <field name="score">
- <field-validator type="double">
- <param name="minInclusive">0.0</param>
- <param name="maxInclusive">100.0</param>
- <message>成绩必须在${minInclusive}和${maxInclusive}之间</message>
- </field-validator>
- </field>
- <field name="email">
- <field-validator type="regex">
- <param name="expression"><![CDATA[(^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-])+((\.com)|(\.cn)|(\.net)|(\.org)|(\.info)|(\.edu)|(\.mil)|(\.gov)|(\.biz)|(\.ws)|(\.us)|(\.tv)|(\.cc)|(\.aero)|(\.arpa)|(\.coop)|(\.int)|(\.jobs)|(\.museum)|(\.name)|(\.pro)|(\.travel)|(\.nato)|(\..{2,3})|(\..{2,3}\..{2,3}))$)]]></param>
- <message>邮箱不合法</message>
- </field-validator>
- </field>
- <field name="registed_date">
- <field-validator type="date">
- <param name="min">1970-01-01</param>
- <param name="max">2019-01-01</param>
- <message>注册日期不合法</message>
- </field-validator>
- </field>
- </validators></span>
与User.java同一目录下的User-userLoginContext-validation.xml
- <span style="font-size: medium;"><?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="requiredstring" short-circuit="true">
- <message>姓名是必填的</message>
- </field-validator>
- <field-validator type="regex">
- <param name="expression"><![CDATA[(^[a-zA-Z_]\w{3,9}$)]]></param>
- <message>姓名不合法</message>
- </field-validator>
- </field>
- <field name="pwd">
- <field-validator type="requiredstring" short-circuit="true">
- <message>密码是必填的</message>
- </field-validator>
- </field>
- </validators></span>