struts2中利用validation框架进行数据校验
1,创建web工程 java EE5,在lib中导入struts2的各个包(参见前面的“sturts2配置”)形成的具体工程结构图如下:
2,创建用户注册模块的视图界面register.jsp registerSuccess.jsp
register.jsp的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="struts" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'register.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <struts:text name="register.jsp.label.heading"/> <struts:fielderror/> <hr/> <center> <struts:form action="register" method="post"> <struts:textfield name="userName" key="register.jsp.label.username"></struts:textfield> <struts:password name="psw1" key="register.jsp.label.psw1"></struts:password> <struts:password name="psw2" key="register.jsp.label.psw2"></struts:password> <struts:textfield name="telNum" key="register.jsp.label.age"></struts:textfield> <struts:textfield name="email" key="register.jsp.label.telnum"></struts:textfield> <struts:submit key="register.jsp.button.submit"></struts:submit> </struts:form> </center> </body> </html>
registerSuccess.jsp的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="struts" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'registerSuccess.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center><struts:text name="registerSuccess.jsp.heading"></struts:text></center> <hr/> <struts:text name="registerSuccess.jsp.label.welcome"/> <struts:property value="userName"/> <struts:fielderror/> </body> </html>
3,在src下创建资源信息文件Application.properties 并创建struts.properties配置文件
Application.properties的内容如下:
register.jsp.label.title=Register Page register.jsp.label.heading=<center><h2>User Register</h2></center> register.jsp.label.username=User Name* register.jsp.label.psw1=Password* register.jsp.label.psw2=Validation Password* register.jsp.label.age=Age register.jsp.label.email=E_Mail* register.jsp.label.telnum=Telephone Number register.jsp.button.submit=Submit register.jsp.button.reset=Reset registerSuccess.jsp.title=Welcome Page registerSuccess.jsp.heading=<center><h2>Welcome to Our System</h2></center> registerSuccess.jsp.label.welcome=Welcome username.required=Please input your user name. username.maxlength=The length of your user name shouldn't exceed 20 characters. psw.required=Please input your password. psw.maxlength=The length of your password shouldn't exceed 20 characters. errors.validwhen=password isn't equal to validation password. sex.required=Please input your sex. age.error=Your age must be in this interval(0,200). tel.error=Please input correct telephone number(7-15 figures). email.required=Please input your E_Mail. email.error=E_Mail illegal. username.exist=This user name exists.
让struts2框架识别资源配置文件的代码为“struts.custom.i18n.resources=Application", struts.properties的代码如下:
struts.action.extension=action
struts.custom.i18n.resources=Application
struts.locale=en_GB
4,创建Action:action.RegisterAction.java, 代码如下:
在RegisterAction类所在路径下创建名为RegisterAction-validation.xml的配置文件,该配置文件的命名规则是:<ActionClassName>-validation.xml,该文件的存放路径要和RegisterAction类在同一路径下,即放在action包中,,具体代码如下:
<?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="userName"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>${getText("username.required")}</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">0</param> <param name="maxLength">20</param> <message>${getText("username.maxlength")}</message> </field-validator> </field> <!-- 检查密码是否为空,输入的两个密码是否一致 --> <field name="psw1"> <field-validator type="requiredstring"> <message>${getText("psw.required")}</message> </field-validator> <field-validator type="fieldexpression"> <param name="expression"><![CDATA[(psw2==psw1)and(psw1!=null)]]></param> <message>${getText("errors.validwhen")}</message> </field-validator> </field> <!-- 检查年龄,年龄在0-200之间 --> <field name="age"> <field-validator type="int"> <param name="min">0</param> <param name="max">200</param> <message>${getText("age.error")}</message> </field-validator> </field> <!-- 检查电话号码,判断是否为0-9之间的7-15位数字 --> <field name="telNum"> <field-validator type="regex"> <param name="expression"><![CDATA[[0-9]{7,15}$]]></param> <message>${getText("tel.error")}</message> </field-validator> </field> <!-- 检查电子邮箱是否合法 --> <field name="email"> <field-validator type="requiredstring"> <message>${getText("email.required")}</message> </field-validator> <field-validator type="email"> <message>${getText("email.error")}</message> </field-validator> </field> </validators>
然后将Struts2的JAR包中的xwork-validation-1.0.2.dtd文件放到和数据校验配置文件同路径下,即放到包action中。
5,为解决中文乱码问题,创建过滤器filter.CharacterEncodingFilter.java
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterEncodingFilter implements Filter {
private String characterEncoding;//编码方式在web.xml中
private boolean enabled;//是否启动filter,初始值在web.xml中
@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
//初始化时加载参数
//从配置文件中读取设置到编码方式
characterEncoding=config.getInitParameter("characterEncoding");
//启动该过滤器完成编码方式到修改
enabled="true".equalsIgnoreCase(characterEncoding.trim())
||"1".equalsIgnoreCase(characterEncoding.trim());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
if(enabled||characterEncoding!=null){
request.setCharacterEncoding(characterEncoding);//设置request编码方式
response.setCharacterEncoding(characterEncoding);//设置response编码方式
}
chain.doFilter(request, response);//doFilter将修改好的request和response参数向下传递;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
characterEncoding=null;
}
}
6, 配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>register.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>struts.action.extension</param-name> <param-value>action</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>characterEncoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>enable</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
7,配置struts.xml (注意配置input)
<?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="main" extends="struts-default"> <action name="register" class="action.RegisterAction"> <result name="input">/register.jsp</result> <result>/registerSuccess.jsp</result> </action></package> </struts> <!-- 这里 struts中必须配置input返回视图,否则会报错, 官方的解释是:if you don't have this,you'll get a:"No result defined for action xxx.xxx.xxx and result input"error -->
8,发布即可。。。
参考资料:
(1)Struts2中的校验框架 :http://blog.csdn.net/jadyer/article/details/6176122
(2)