Struts2 使用Validation框架验证数据
2015-12-06 21:38
671 查看
在采用struts的xml配置方式校验数据时,发现怎么也不起作用。无法按照正常流程,走到input指向的页面。
一 问题的解决
很多博客说明了自己查找的方式,最后都指明了是因为配置文件格式不正确的原因。出现这种问题的时候,应该从下面4个部分考虑:
1:文件名是否是 LogInAction-validation.xml 第一部分的名字必须与action类名对应一致。
2:struts.xml中同一个action下面,要配置input类型的返回结果,如同:
<action name="login" class="com.allen.ssh.action.LogInAction">
<result name="success">/Welcome.jsp</result>
<result name="error">/Register.jsp</result>
<result name="input">/Register.jsp</result>
</action>
3:然后是检查 LogInAction-validation.xml 中指定的属性名字,是否与JSP页面中的属性名字一致。
4:然后是 LogInAction-validation.xml 文件格式是否正确,主要是指如下这一部分:
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
A:在Struts2的框架汇中,开发者可以通过继承ActionSupport()类,并重写validate()方法来完成输入校验。使用在Action中重写Validate()或者 validateXxx()方法实现校验对某个方法起作用。
例如:validate()方法会对action中的所有 逻辑处理方法起作用 比如:execute() , login()
B:采用Struts2的内置校验器 也就是配置文件 来实现校验
-----------Validate()------------------------
1.在Struts2的框架汇中,专门用来校验数据的方法是validate(),开发者可以通过继承ActionSupport()类,并重写validate()方法来完成输入校验。
validate()方法会对action中的所有 逻辑处理方法起作用 比如:execute() , login()
2.action.
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.xml.internal.fastinfoset.stax.events.Util;
public class ValidateAction extends ActionSupport {
private String name;
private String pwd;
private Date date;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
@Override
public void validate() {
if(date==null || date.after(new Date())){
addFieldError("date", "出生日期无效!");
}
if(pwd==null || Util.isEmptyString(pwd)){
addFieldError("pwd", "密码不能为空!");
}
}
}
3.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="validateAction" class="com.sh.action.ValidateAction">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
4.login.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="validateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
复合生日:<s:textfield name="pwd"/><br/>
常用日期:<s:textfield name="date"/><br/>
常用日期2:<sx:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd hh:mm:ss"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5访问
--http://localhost:8080/Struts2_validate/index.jsp
-----------ValidateXxxx()------------------------
6.只对action中某一个处理方法 进行校验 测试login(如果 valudate()不注释,就会对所有的方法起作用)
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.Date;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.xml.internal.fastinfoset.stax.events.Util;
public class ValidateAction extends ActionSupport {
private String name;
private String pwd;
private Date date;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
@Override //会对所有的 方法都有作用 比如 execute login
public void validate() {
if(date==null || date.after(new Date())){
addFieldError("date", "出生日期无效!");
}
if(pwd==null || Util.isEmptyString(pwd)){
addFieldError("pwd", "密码不能为空!");
}
}
//登陆方法
public String login(){
return SUCCESS;
}
//只对登录方法进行校验
public void validateLogin(){
if(name!=null && !Pattern.matches("\\w{6,15}", name.trim())){
addFieldError(name, "validateLogin()方法的作用");
}
}
//get set
}
7.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="validateAction" class="com.sh.action.ValidateAction">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="validateLoginAction" class="com.sh.action.ValidateAction" method="login">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
8.访问
--http://localhost:8080/Struts2_validate/index.jsp
--如果不输入端额话,将会出现指定的错误信息。
-----------Struts2内置校验器------------------------
struts2的所有校验器在
xwork-core.jar/com.opensymphony.xwork2.validator.validators/default.xml 中有定义。
9.Struts2内置校验器的种类
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
required:必填校验器
requiredstring:必填字符串校验器
stringlength: 字符串长度校验器
int:整数校验器
date:日期校验器
expression:表达式校验器
fieldexpression:字段表达式校验器
email: 邮件地址校验器
url:网址校验器
conversioin:转换校验器
regex:正则表达式校验器
10.使用Struts2内置校验器
字段校验器配置风格
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<validators>
<field name="被校验的字段">
<field-validator type="校验器的类型">
<param name="参数名">参数值</param>
<message> 提示信息</message>
</field-validator>
</field>
<!--下一个要验证的字段-->
</validators>
11.非字段校验器配置风格
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<valiators>
<validator type="校验器类型名">
<!--fieldName固定的 N必须大写-->
<param name="fieldName">需要被校验的字段</param>
<!--下面的param元素可以有0个或者多个-->
<param name="参数名">参数值</param>
<message key="I18NKey">提示信息</message>
</validator>
</validators>
12.使用内置校验器需要定义 ActionName-validate.xml文件 在其中定义 字段校验器和非字段校验器
--------使用 字段校验器 --------
13.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class InnerValidatorAction extends ActionSupport {
private int age;
private String name;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
14.InnerValidatorAction-validation.xml 定义上面 aciton的校验文件
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<!-- 根据字段配置校验 -->
<!--
short-circuit="true" :表示短路,即下面的: 如果age 不是整数 就不会验证 age 的大小范围,这样我们的错误信息只有一个 (类似: if... else if...)
short-circuit="false" :表示不短路(默认): 即下面的: 如果 age 不是整数,还会继续判断age的大小范围 这样页面就有两个错误信息 (类似if... if..)
-->
<!-- 验证字段必须为整数 -->
<!--使用conversion校验器-->
<field name="age">
<field-validator type="conversion" short-circuit="true">
<message>年龄必须为整数</message>
</field-validator>
</field>
<!-- 验证字段必须的大小范围 -->
<!--使用int校验器-->
<field name="age">
<field-validator type="int" short-circuit="true">
<param name="min">18</param>
<param name="max">100</param>
<message>年龄必须在${min}到${max}之间</message>
</field-validator>
</field>
<!-- 验证name字段必须为string类型 -->
<!--使用requiredstring校验器-->
<field name="name">
<field-validator type="requiredstring" short-circuit="true">
<message>姓名不能为空</message>
</field-validator>
</field>
<!--使用stringlength校验器-->
<field name="name">
<field-validator type="stringlength" short-circuit="true">
<param name="maxLength">15</param>
<param name="minLength">6</param>
<message>姓名长度必须为${minLength}到${maxLength}之间!</message>
</field-validator>
</field>
</validators>
15.strust.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="true"/>
<constant name="struts.convention.classes.reload" value="false" />
<package name="default" extends="struts-default">
<action name="innerValidateAction" class="com.sh.action.InnerValidatorAction">
<result>/success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
16.login.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="innerValidateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
17.访问上
--http://localhost:8080/Struts2_validator/login.jsp
如果不输入就可以看到 验证的消息
18.使用 非字段校验器 InnerValidator1Action-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<!--对于 字符类型的校验 个人发现 如果不定义requiredstring这个类型的校验 下面的 stringlength校验器 不起作用 --->
<validator type="requiredstring">
<param name="fieldName">name</param>
<message>姓名不能为空!</message>
</validator>
<validator type="stringlength">
<param name="fieldName">name</param>
<param name="maxLength">15</param>
<param name="minLength">6</param>
<message>姓名长度为${minLength}到${maxLength}之间!</message>
</validator>
----------复合属性 校验------------
A:使用字段校验器
1.pojo
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.pojo;
public class User {
private String name;
private String pwd;
private String mobile;
//get set
}
2.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class UserAction extends ActionSupport {
private User user;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
3.编写UserAction-validation.xml 校验文件
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="user.mobile">
<field-validator type="requiredstring">
<!--去掉空格 -->
<param name="trim">true</param>
<message>手机号不能为空</message>
</field-validator>
<field-validator type="regex">
<param name="expression"><![CDATA[^1[358]\d{9}$]]></param>
<message>手机号格式不正确</message>
</field-validator>
</field>
</validators>
4.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="userAction" method="post" theme="simple">
用户名:<s:textfield name="user.name"/><br/>
密码:<s:textfield name="user.pwd"/><br/>
手机版:<s:textfield name="user.mobile"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.访问
---http://localhost:8080/Struts2_validator/login2.jsp
--如果不填 或者格式错误会有提示的
B使用 visitor 校验复合属性
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class VisitorAction extends ActionSupport{
private User user;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
2.定义 aciton校验文件 VisitorAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="user">
<field-validator type="visitor">
<!--复合类型属性的上下文校验名称 -->
<param name="context">visitorContext</param>
<!--是否添加前缀 如果true 就使用message-->
<param name="appendPrefix">true</param>
<message>联系人:</message>
</field-validator>
</field>
</validators>
3.定义实体类User 的上下文校验文件User-visitorContext-validation.xml (和User同目录)
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<message>姓名不能为空!</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">10</param>
<param name="max">100</param>
<message>年龄为${min}到${max}之间</message>
</field-validator>
</field>
</validators>
4.login3.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="visitorAction" method="post" theme="simple">
用户名:<s:textfield name="user.name"/><br/>
年龄:<s:textfield name="user.age"/><br/>
手机版:<s:textfield name="user.mobile"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.struts.xml
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="visitorAction" class="com.sh.action.VisitorAction">
<result>/index.jsp</result>
<result name="input">/login3.jsp</result>
</action>
</package>
</struts>
6.访问
--http://localhost:8080/Struts2_validator/login3.jsp
--没有输入的时候会看到验证信息
---------------集合属性校验---------------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class VisitorListAction extends ActionSupport {
private List<User> userlist;
@Override
public String execute() throws Exception {
System.out.println("1");
return super.execute();
}
//get set
}
2.定义action的校验文 VisitorListAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="userlist">
<field-validator type="visitor">
<!--复合类型属性的上下文校验名称 -->
<param name="context">visitorContext2</param>
<!--是否添加前缀 如果true 就使用message-->
<param name="appendPrefix">true</param>
<message>联系人:</message>
</field-validator>
</field>
</validators>
3.定义集合中的对象 描述属性文件VisitorListAction-conversion.properties
(命名规则为 ActionNaqme-conversion.properties 具体的在 三十五 章里介绍)
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
Element_userlist=com.sh.pojo.User
4.定义集合对象校验文件User-visitorContext2-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<message>姓名不能为空!</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">20</param>
<param name="max">120</param>
<message>年龄为${min}到${max}之间</message>
</field-validator>
</field>
</validators>
5.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.devMode" value="true"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="visitorListAction" class="com.sh.action.VisitorListAction">
<result>/success.jsp</result>
<result name="input">/visitorList.jsp</result>
</action>
</package>
</struts>
6.visitorList.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<form action="${pageContext.request.contextPath}/visitorListAction.action" method="post">
<ul style="list-style:none; text-align: center;">
<li style="float: left;width: 155px">用户名</li>
<li style="float: left;width: 155px">密码</li>
<li style="float: left;width: 155px">年龄</li>
<li style="float: left;width: 155px">生日</li>
<li style="float: left;width: 155px">地址</li>
</ul>
<div style="clear: both;"></div>
<c:forEach items="new int[]{0,0,0,0}" varStatus="st">
<ul style="list-style:none;">
<li style="float: left">
<input name="userlist[${st.index}].name"/>
</li>
<li style="float: left">
<input name="userlist[${st.index}].pwd" />
</li>
<li style="float: left">
<input name="userlist[${st.index}].age"/>
</li>
<li style="float: left">
<input name="userlist[${st.index}].birthday" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'});"/>
</li>
<li>
<input name="userlist[${st.index}].address" />
</li>
</ul>
</c:forEach>
<div><input type="submit"/></div>
</body>
7.访问
--http://localhost:8080/Struts2_validator/visitorList.jsp
--可以看到所设定的所有被校验的字段
-------------内置校验器 : required--------
1.用于要求户必须有值,(非null),
参数:fieldName:校验的字段名, 如果是字段校验则不用指定该参数。
2.用户 验证 一个对象是否为空
3.不能用来校验 string 类型的必填. 如果要校验 则使用 requiredstring。
4. required要求的是一个对象不能为null,它可以验证像Date类型的对象
5.requiredstring只是对字符串做限制
有参数 maxLength
minLength
trim
-------------内置校验器 :conversion-------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class IntAction extends ActionSupport {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
2,校验文件 IntAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="age">
<field-validator type="conversion">
<!--复合类型属性的上下文校验名称 -->
<param name="repopulateField">true</param>
<!--是否添加前缀 如果true 就使用message-->
<message>年龄必须为整数:</message>
</field-validator>
</field>
</validators>
3.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<action name="intAction" class="com.sh.action.IntAction">
<result name="success">/success.jsp</result>
<result name="input">/int.jsp</result>
</action>
4.int.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
==================使用内置校验器 类型转转校验器========================
<s:fielderror/>
<s:form action="intAction" method="post" theme="simple">
用户名:<s:textfield name="userName"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.访问
--http://localhost:8383/Struts2_validator/int.jsp
--如果不输入 就出现 年龄必须为整数:错误信息
--如果输入 字符 就会出现两个 错误信息
---其中一个错误信息是 Struts2框架的错误信息为英文 为了解决这个问题 下面可以 改为只能够为 中文 或者 置空 这样就只有一个错误提示 或者 连个中文提示
6.定义IntAction_zh_CN.properties
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
invalid.fieldvalue.age=properties文件:年龄必须整数
#或者xia'm
#invalid.fieldvalue.age=
这样就会提示两个中文错误信息 (不过意思是一样的)
-------------------Date--------------
1,校验文件 DateAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="age">
<field-validator type="date">
<!--复合类型属性的上下文校验名称 -->
<param name="max">2012-12-20</param>
<param name="min">1997-01-01</param>
<message>生日应在 ${min}到${max}之间</message>
</field-validator>
</field>
</validators>
-------------------Emal 和 URL--------------------
1.EmailUrlAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="email">
<field-validator type="email">
<message>邮件地址不正确</message>
</field-validator>
</field>
<field name="url">
<field-validator type="url">
<message>网址格式不正确</message>
</field-validator>
</field>
</validators>
------------------------expression 和 fieldexpression----------
expression 不能使用字段校验风格配置
fieldexpression 两种都可以使用
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<validator type="expression">
<param name="expression">max2 > min2</param>
<message>max1要大于 min1</message>
</validator>
<field name="max2">
<field-validator type="fieldexpression">
<param name="expression">max2 > min2</param>
<message>max2要大于 min2</message>
</field-validator>
</field>
</validators>
--------------------double----------------------
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<field name="sal">
<!-- 10<=sal<=100 -->
<field-validator type="double">
<!-- 允许的最大值 -->
<param name="minInclusive">10</param>
<!-- 允许的最大值 -->
<param name="maxInclusive">100</param>
<message>${minInclusive}大于等于 薪水 小于等于 ${maxInclusive}</message>
</field-validator>
<!-- 10<sal<100 -->
<field-validator type="double">
<!-- 允许的最大值 -->
<param name="minExclusive">10</param>
<!-- 允许的最大值 -->
<param name="maxExclusive">100</param>
<message>"${minInclusive}大于 薪水 小于 ${maxInclusive}"</message>
</field-validator>
</field>
-----------------------regex-----------------------
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<field name="mycode">
<field-validator type="regex">
<param name="expression">
<![CDATA[[0-9]\d{5}(?!\d)]]>
</param>
<message>不是有效的邮政编码!</message>
</field-validator>
</field>
------------------自定义校验器--------------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class MyValidateAction extends ActionSupport {
private String name;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
2.自定义一个校验器类 继承相应的 校验接口 就可以了 MyValidate .java
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.validate;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class MyValidate extends FieldValidatorSupport {
private String name; //对应<param name="name"/>
public void validate(Object object) throws ValidationException {
// TODO Auto-generated method stub
String fieldName=super.getFieldName();
String value=super.getFieldValue(fieldName, object).toString();
if(!name.equals(value)){
super.addFieldError(super.getFieldName(), object);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.在框架中注册自定义的校验器类 编写 validators.xml (文件名固定)
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Definition 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">
<validators>
<validator name="myValidate" class="com.sh.validate.MyValidate"></validator>
</validators>
4.使用自定义校验器类 编写 校验文件 MyValidateAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="myValidate">
<param name="name">admin</param>
<message>姓名必须为${name}!</message>
</field-validator>
</field>
</validators>
5.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<action name="myValidateAction" class="com.sh.action.MyValidateAction">
<result name="success">/success.jsp</result>
<result name="input">/myValidator.jsp</result>
</action>
6.myValidator.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
==================使用内置校验器 自定义校验器的使用========================
<s:fielderror/>
<s:form action="myValidateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
7.访问
--http://localhost:8383/Struts2_validator/myValidator.jsp
--如果输入就会出现 姓名必须为admin!的错误信息
一 问题的解决
很多博客说明了自己查找的方式,最后都指明了是因为配置文件格式不正确的原因。出现这种问题的时候,应该从下面4个部分考虑:
1:文件名是否是 LogInAction-validation.xml 第一部分的名字必须与action类名对应一致。
2:struts.xml中同一个action下面,要配置input类型的返回结果,如同:
<action name="login" class="com.allen.ssh.action.LogInAction">
<result name="success">/Welcome.jsp</result>
<result name="error">/Register.jsp</result>
<result name="input">/Register.jsp</result>
</action>
3:然后是检查 LogInAction-validation.xml 中指定的属性名字,是否与JSP页面中的属性名字一致。
4:然后是 LogInAction-validation.xml 文件格式是否正确,主要是指如下这一部分:
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
A:在Struts2的框架汇中,开发者可以通过继承ActionSupport()类,并重写validate()方法来完成输入校验。使用在Action中重写Validate()或者 validateXxx()方法实现校验对某个方法起作用。
例如:validate()方法会对action中的所有 逻辑处理方法起作用 比如:execute() , login()
B:采用Struts2的内置校验器 也就是配置文件 来实现校验
-----------Validate()------------------------
1.在Struts2的框架汇中,专门用来校验数据的方法是validate(),开发者可以通过继承ActionSupport()类,并重写validate()方法来完成输入校验。
validate()方法会对action中的所有 逻辑处理方法起作用 比如:execute() , login()
2.action.
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.xml.internal.fastinfoset.stax.events.Util;
public class ValidateAction extends ActionSupport {
private String name;
private String pwd;
private Date date;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
@Override
public void validate() {
if(date==null || date.after(new Date())){
addFieldError("date", "出生日期无效!");
}
if(pwd==null || Util.isEmptyString(pwd)){
addFieldError("pwd", "密码不能为空!");
}
}
}
3.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="validateAction" class="com.sh.action.ValidateAction">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
4.login.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="validateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
复合生日:<s:textfield name="pwd"/><br/>
常用日期:<s:textfield name="date"/><br/>
常用日期2:<sx:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd hh:mm:ss"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5访问
--http://localhost:8080/Struts2_validate/index.jsp
-----------ValidateXxxx()------------------------
6.只对action中某一个处理方法 进行校验 测试login(如果 valudate()不注释,就会对所有的方法起作用)
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.Date;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.xml.internal.fastinfoset.stax.events.Util;
public class ValidateAction extends ActionSupport {
private String name;
private String pwd;
private Date date;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
@Override //会对所有的 方法都有作用 比如 execute login
public void validate() {
if(date==null || date.after(new Date())){
addFieldError("date", "出生日期无效!");
}
if(pwd==null || Util.isEmptyString(pwd)){
addFieldError("pwd", "密码不能为空!");
}
}
//登陆方法
public String login(){
return SUCCESS;
}
//只对登录方法进行校验
public void validateLogin(){
if(name!=null && !Pattern.matches("\\w{6,15}", name.trim())){
addFieldError(name, "validateLogin()方法的作用");
}
}
//get set
}
7.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="validateAction" class="com.sh.action.ValidateAction">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="validateLoginAction" class="com.sh.action.ValidateAction" method="login">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
8.访问
--http://localhost:8080/Struts2_validate/index.jsp
--如果不输入端额话,将会出现指定的错误信息。
-----------Struts2内置校验器------------------------
struts2的所有校验器在
xwork-core.jar/com.opensymphony.xwork2.validator.validators/default.xml 中有定义。
9.Struts2内置校验器的种类
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
required:必填校验器
requiredstring:必填字符串校验器
stringlength: 字符串长度校验器
int:整数校验器
date:日期校验器
expression:表达式校验器
fieldexpression:字段表达式校验器
email: 邮件地址校验器
url:网址校验器
conversioin:转换校验器
regex:正则表达式校验器
10.使用Struts2内置校验器
字段校验器配置风格
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<validators>
<field name="被校验的字段">
<field-validator type="校验器的类型">
<param name="参数名">参数值</param>
<message> 提示信息</message>
</field-validator>
</field>
<!--下一个要验证的字段-->
</validators>
11.非字段校验器配置风格
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<valiators>
<validator type="校验器类型名">
<!--fieldName固定的 N必须大写-->
<param name="fieldName">需要被校验的字段</param>
<!--下面的param元素可以有0个或者多个-->
<param name="参数名">参数值</param>
<message key="I18NKey">提示信息</message>
</validator>
</validators>
12.使用内置校验器需要定义 ActionName-validate.xml文件 在其中定义 字段校验器和非字段校验器
--------使用 字段校验器 --------
13.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class InnerValidatorAction extends ActionSupport {
private int age;
private String name;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
14.InnerValidatorAction-validation.xml 定义上面 aciton的校验文件
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<!-- 根据字段配置校验 -->
<!--
short-circuit="true" :表示短路,即下面的: 如果age 不是整数 就不会验证 age 的大小范围,这样我们的错误信息只有一个 (类似: if... else if...)
short-circuit="false" :表示不短路(默认): 即下面的: 如果 age 不是整数,还会继续判断age的大小范围 这样页面就有两个错误信息 (类似if... if..)
-->
<!-- 验证字段必须为整数 -->
<!--使用conversion校验器-->
<field name="age">
<field-validator type="conversion" short-circuit="true">
<message>年龄必须为整数</message>
</field-validator>
</field>
<!-- 验证字段必须的大小范围 -->
<!--使用int校验器-->
<field name="age">
<field-validator type="int" short-circuit="true">
<param name="min">18</param>
<param name="max">100</param>
<message>年龄必须在${min}到${max}之间</message>
</field-validator>
</field>
<!-- 验证name字段必须为string类型 -->
<!--使用requiredstring校验器-->
<field name="name">
<field-validator type="requiredstring" short-circuit="true">
<message>姓名不能为空</message>
</field-validator>
</field>
<!--使用stringlength校验器-->
<field name="name">
<field-validator type="stringlength" short-circuit="true">
<param name="maxLength">15</param>
<param name="minLength">6</param>
<message>姓名长度必须为${minLength}到${maxLength}之间!</message>
</field-validator>
</field>
</validators>
15.strust.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<constant name="struts.devMode" value="true"/>
<constant name="struts.convention.classes.reload" value="false" />
<package name="default" extends="struts-default">
<action name="innerValidateAction" class="com.sh.action.InnerValidatorAction">
<result>/success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
16.login.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="innerValidateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
17.访问上
--http://localhost:8080/Struts2_validator/login.jsp
如果不输入就可以看到 验证的消息
18.使用 非字段校验器 InnerValidator1Action-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<!--对于 字符类型的校验 个人发现 如果不定义requiredstring这个类型的校验 下面的 stringlength校验器 不起作用 --->
<validator type="requiredstring">
<param name="fieldName">name</param>
<message>姓名不能为空!</message>
</validator>
<validator type="stringlength">
<param name="fieldName">name</param>
<param name="maxLength">15</param>
<param name="minLength">6</param>
<message>姓名长度为${minLength}到${maxLength}之间!</message>
</validator>
----------复合属性 校验------------
A:使用字段校验器
1.pojo
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.pojo;
public class User {
private String name;
private String pwd;
private String mobile;
//get set
}
2.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class UserAction extends ActionSupport {
private User user;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
3.编写UserAction-validation.xml 校验文件
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="user.mobile">
<field-validator type="requiredstring">
<!--去掉空格 -->
<param name="trim">true</param>
<message>手机号不能为空</message>
</field-validator>
<field-validator type="regex">
<param name="expression"><![CDATA[^1[358]\d{9}$]]></param>
<message>手机号格式不正确</message>
</field-validator>
</field>
</validators>
4.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="userAction" method="post" theme="simple">
用户名:<s:textfield name="user.name"/><br/>
密码:<s:textfield name="user.pwd"/><br/>
手机版:<s:textfield name="user.mobile"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.访问
---http://localhost:8080/Struts2_validator/login2.jsp
--如果不填 或者格式错误会有提示的
B使用 visitor 校验复合属性
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class VisitorAction extends ActionSupport{
private User user;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
2.定义 aciton校验文件 VisitorAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="user">
<field-validator type="visitor">
<!--复合类型属性的上下文校验名称 -->
<param name="context">visitorContext</param>
<!--是否添加前缀 如果true 就使用message-->
<param name="appendPrefix">true</param>
<message>联系人:</message>
</field-validator>
</field>
</validators>
3.定义实体类User 的上下文校验文件User-visitorContext-validation.xml (和User同目录)
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<message>姓名不能为空!</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">10</param>
<param name="max">100</param>
<message>年龄为${min}到${max}之间</message>
</field-validator>
</field>
</validators>
4.login3.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<s:form action="visitorAction" method="post" theme="simple">
用户名:<s:textfield name="user.name"/><br/>
年龄:<s:textfield name="user.age"/><br/>
手机版:<s:textfield name="user.mobile"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.struts.xml
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.devMode" value="false"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="visitorAction" class="com.sh.action.VisitorAction">
<result>/index.jsp</result>
<result name="input">/login3.jsp</result>
</action>
</package>
</struts>
6.访问
--http://localhost:8080/Struts2_validator/login3.jsp
--没有输入的时候会看到验证信息
---------------集合属性校验---------------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.sh.pojo.User;
public class VisitorListAction extends ActionSupport {
private List<User> userlist;
@Override
public String execute() throws Exception {
System.out.println("1");
return super.execute();
}
//get set
}
2.定义action的校验文 VisitorListAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="userlist">
<field-validator type="visitor">
<!--复合类型属性的上下文校验名称 -->
<param name="context">visitorContext2</param>
<!--是否添加前缀 如果true 就使用message-->
<param name="appendPrefix">true</param>
<message>联系人:</message>
</field-validator>
</field>
</validators>
3.定义集合中的对象 描述属性文件VisitorListAction-conversion.properties
(命名规则为 ActionNaqme-conversion.properties 具体的在 三十五 章里介绍)
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
Element_userlist=com.sh.pojo.User
4.定义集合对象校验文件User-visitorContext2-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<message>姓名不能为空!</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">20</param>
<param name="max">120</param>
<message>年龄为${min}到${max}之间</message>
</field-validator>
</field>
</validators>
5.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
<constant name="struts.devMode" value="true"/>
<constant name="struts.convention.classes.reload" value="true" />
<package name="default" extends="struts-default">
<action name="visitorListAction" class="com.sh.action.VisitorListAction">
<result>/success.jsp</result>
<result name="input">/visitorList.jsp</result>
</action>
</package>
</struts>
6.visitorList.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
<s:fielderror/>
<form action="${pageContext.request.contextPath}/visitorListAction.action" method="post">
<ul style="list-style:none; text-align: center;">
<li style="float: left;width: 155px">用户名</li>
<li style="float: left;width: 155px">密码</li>
<li style="float: left;width: 155px">年龄</li>
<li style="float: left;width: 155px">生日</li>
<li style="float: left;width: 155px">地址</li>
</ul>
<div style="clear: both;"></div>
<c:forEach items="new int[]{0,0,0,0}" varStatus="st">
<ul style="list-style:none;">
<li style="float: left">
<input name="userlist[${st.index}].name"/>
</li>
<li style="float: left">
<input name="userlist[${st.index}].pwd" />
</li>
<li style="float: left">
<input name="userlist[${st.index}].age"/>
</li>
<li style="float: left">
<input name="userlist[${st.index}].birthday" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'});"/>
</li>
<li>
<input name="userlist[${st.index}].address" />
</li>
</ul>
</c:forEach>
<div><input type="submit"/></div>
</body>
7.访问
--http://localhost:8080/Struts2_validator/visitorList.jsp
--可以看到所设定的所有被校验的字段
-------------内置校验器 : required--------
1.用于要求户必须有值,(非null),
参数:fieldName:校验的字段名, 如果是字段校验则不用指定该参数。
2.用户 验证 一个对象是否为空
3.不能用来校验 string 类型的必填. 如果要校验 则使用 requiredstring。
4. required要求的是一个对象不能为null,它可以验证像Date类型的对象
5.requiredstring只是对字符串做限制
有参数 maxLength
minLength
trim
-------------内置校验器 :conversion-------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class IntAction extends ActionSupport {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
2,校验文件 IntAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="age">
<field-validator type="conversion">
<!--复合类型属性的上下文校验名称 -->
<param name="repopulateField">true</param>
<!--是否添加前缀 如果true 就使用message-->
<message>年龄必须为整数:</message>
</field-validator>
</field>
</validators>
3.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<action name="intAction" class="com.sh.action.IntAction">
<result name="success">/success.jsp</result>
<result name="input">/int.jsp</result>
</action>
4.int.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
==================使用内置校验器 类型转转校验器========================
<s:fielderror/>
<s:form action="intAction" method="post" theme="simple">
用户名:<s:textfield name="userName"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
5.访问
--http://localhost:8383/Struts2_validator/int.jsp
--如果不输入 就出现 年龄必须为整数:错误信息
--如果输入 字符 就会出现两个 错误信息
---其中一个错误信息是 Struts2框架的错误信息为英文 为了解决这个问题 下面可以 改为只能够为 中文 或者 置空 这样就只有一个错误提示 或者 连个中文提示
6.定义IntAction_zh_CN.properties
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
invalid.fieldvalue.age=properties文件:年龄必须整数
#或者xia'm
#invalid.fieldvalue.age=
这样就会提示两个中文错误信息 (不过意思是一样的)
-------------------Date--------------
1,校验文件 DateAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="age">
<field-validator type="date">
<!--复合类型属性的上下文校验名称 -->
<param name="max">2012-12-20</param>
<param name="min">1997-01-01</param>
<message>生日应在 ${min}到${max}之间</message>
</field-validator>
</field>
</validators>
-------------------Emal 和 URL--------------------
1.EmailUrlAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="email">
<field-validator type="email">
<message>邮件地址不正确</message>
</field-validator>
</field>
<field name="url">
<field-validator type="url">
<message>网址格式不正确</message>
</field-validator>
</field>
</validators>
------------------------expression 和 fieldexpression----------
expression 不能使用字段校验风格配置
fieldexpression 两种都可以使用
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<validator type="expression">
<param name="expression">max2 > min2</param>
<message>max1要大于 min1</message>
</validator>
<field name="max2">
<field-validator type="fieldexpression">
<param name="expression">max2 > min2</param>
<message>max2要大于 min2</message>
</field-validator>
</field>
</validators>
--------------------double----------------------
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<field name="sal">
<!-- 10<=sal<=100 -->
<field-validator type="double">
<!-- 允许的最大值 -->
<param name="minInclusive">10</param>
<!-- 允许的最大值 -->
<param name="maxInclusive">100</param>
<message>${minInclusive}大于等于 薪水 小于等于 ${maxInclusive}</message>
</field-validator>
<!-- 10<sal<100 -->
<field-validator type="double">
<!-- 允许的最大值 -->
<param name="minExclusive">10</param>
<!-- 允许的最大值 -->
<param name="maxExclusive">100</param>
<message>"${minInclusive}大于 薪水 小于 ${maxInclusive}"</message>
</field-validator>
</field>
-----------------------regex-----------------------
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<field name="mycode">
<field-validator type="regex">
<param name="expression">
<![CDATA[[0-9]\d{5}(?!\d)]]>
</param>
<message>不是有效的邮政编码!</message>
</field-validator>
</field>
------------------自定义校验器--------------
1.action
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
public class MyValidateAction extends ActionSupport {
private String name;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
//get set
}
2.自定义一个校验器类 继承相应的 校验接口 就可以了 MyValidate .java
Java代码
![](http://takeme.iteye.com/images/icon_star.png)
package com.sh.validate;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class MyValidate extends FieldValidatorSupport {
private String name; //对应<param name="name"/>
public void validate(Object object) throws ValidationException {
// TODO Auto-generated method stub
String fieldName=super.getFieldName();
String value=super.getFieldValue(fieldName, object).toString();
if(!name.equals(value)){
super.addFieldError(super.getFieldName(), object);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.在框架中注册自定义的校验器类 编写 validators.xml (文件名固定)
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Definition 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">
<validators>
<validator name="myValidate" class="com.sh.validate.MyValidate"></validator>
</validators>
4.使用自定义校验器类 编写 校验文件 MyValidateAction-validation.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="name">
<field-validator type="myValidate">
<param name="name">admin</param>
<message>姓名必须为${name}!</message>
</field-validator>
</field>
</validators>
5.struts.xml
Xml代码
![](http://takeme.iteye.com/images/icon_star.png)
<action name="myValidateAction" class="com.sh.action.MyValidateAction">
<result name="success">/success.jsp</result>
<result name="input">/myValidator.jsp</result>
</action>
6.myValidator.jsp
Html代码
![](http://takeme.iteye.com/images/icon_star.png)
<body>
==================使用内置校验器 自定义校验器的使用========================
<s:fielderror/>
<s:form action="myValidateAction" method="post" theme="simple">
用户名:<s:textfield name="name"/><br/>
年龄:<s:textfield name="age"/><br/>
<s:submit value="提交"/>
</s:form>
</body>
7.访问
--http://localhost:8383/Struts2_validator/myValidator.jsp
--如果输入就会出现 姓名必须为admin!的错误信息
相关文章推荐
- Eclipse快捷键大全(转载)
- Java 自限定的类型
- 关于Java的多线程的创建
- Java多线程初学者指南(7):向线程传递数据的三种方法
- Error:(3, 22) compileSdkVersion android-22 requires compiling with JDK 7
- javaday07-面向对象2
- Spring mvc
- 如何在eclipse上使用egit插件
- Spring Boot自定义错误页面,Whitelabel Error Page处理方式
- java字符串传值问题
- java中的抽象类和抽象方法
- 开发Eclipse Plugin,实现属性文件的切换
- Java Math 常用
- super与this的区别(不知道你就out了)
- java scanner 输入多行
- java中类的加载机制
- 分支语句 (if) 练习 Java代码
- 十则交叉验证语料的划分
- 【LWJGL官方教程】纹理
- Eclipse快捷键