一、数据验证
1.1、为什么要进行数据验证
对数据的合法性进行检查,只允许合法的数据进入应用程序
1.2、在哪里实现数据验证
客户端验证:
数据提交前在客户端验证
可使用JavaScript或者JQuery实现
特点:减少客户等待时间,减小服务器压力
服务器端验证:
在数据提交后服务器端验证
特点:防止“绕过”客户端验证提交非法数据
可以在服务器端处理数据前确保数据的合法性
1.3、Struts2有两种方式实现服务器端数据验证
- 使用ActionSupport编码实现验证
- 使用验证框架实现验证
二、使用ActionSupport实现验证
- 在Action类的业务方法中直接验证
- 重写Validate()方法
- 使用validateXxx()方法
2.1、添加错误信息
addFieldError(String fieldName,String errorMessage),添加字段的错误信息
addActionError(String anErrorMessage),添加与Action所处理业务相关的错误信息
2.2、在页面输出验证结果
- <s:fielderror/>输出一个或者所胡字段的错误信息
- <s:actionerror/>输出所有Action的错误信息
2.3、action的配置
<result name="input">xxx.jsp</result>
三、ActionSupport验证简单实现
3.1、业务方法中较验
实体类
package com.pb.entity; /* * 用户类 */ public class User { private String username; //用户名 private String password; //密码 private Integer age; //年龄 private String email; //邮箱 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; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册页面</title> </head> <body> <!-- 判断字段是否有错误信息--> <s:if test="hasFieldErrors()"> <h1 align="center">输出错误字段信息</h1> <div align="center" style="color:blue;"> 使用s:fielderror输出一个指定的错误信息 <s:fielderror name="user.username" /> 使用s:fielderror输出全部的错误信息 <s:fielderror /> </div> </s:if> <!-- 判断action是否有错误 --> <s:if test="hasActionErrors()"> <h1 align="center">输出错误Action信息</h1> <div align="center" style="color:gray;"> 使用s:actionerror输出action相关的错误信息 <s:actionerror/> </div> </s:if> <h1>使用execute业务方法直接较验</h1> <s:form action="register.action" method="post" > <s:textfield label="用户名" name="user.username"/> <s:password label="密码" name="user.password"/> <s:textfield label="年龄" name="user.age" /> <s:textfield label="邮箱" name="user.email"/> <s:submit value="提交" /><s:reset value="重置" /><br/> </s:form> <s:debug/> </body> </html>
UserAction
package com.pb.web.action; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; import com.pb.entity.User; public class UserAction extends ActionSupport { private User user; @Override public String execute() throws Exception { if(null==user.getUsername() || "".equals(user.getUsername())){ this.addFieldError("user.username", "用户名不能为空!"); } if(null==user.getPassword() || "".equals(user.getPassword())){ this.addFieldError("user.password", "密码不能为空!"); } String ageStr="^\\d{1,3}$"; Pattern ageReg=Pattern.compile(ageStr); Matcher ageMatcher=ageReg.matcher(user.getAge()+""); if(!ageMatcher.matches()){ this.addFieldError("user.age", "年龄只能是数字,并只能为1-200之间!"); } if(null==user.getAge()){ this.addFieldError("user.age", "年龄不能为空!"); } String emaString="^\\[email protected]\\w+(.\\w{2,3}){1,2}$"; Pattern emailReg=Pattern.compile(emaString); Matcher emailMatcher=emailReg.matcher(user.getEmail()); if(!emailMatcher.matches()){ this.addFieldError("user.email", "邮箱格式不正确"); } if(this.hasErrors()){ this.addActionError("输入的注册信息有误"); return INPUT; } return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
struts.xml
<struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="register" class="com.pb.web.action.UserAction"> <result name="input">/register.jsp</result> <result name="success">/registerSuccess.jsp</result> </action> </package> </struts>
四、在Validate()方法中实现验证
- 重写ActionSupport类的validate()方法
- 在validate()方法中实现验证
- 将数据验证和业务处理分离
- 添加与显示错误信息的方式不变
接收参数时,数据转换失败也会调用validate()方法
validate()方法验证不通过不会执行业务方法
4.1、更改之前实现validate()验证
package com.pb.web.action; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; import com.pb.entity.User; public class UserAction1 extends ActionSupport { private User user; @Override public String execute() throws Exception { System.out.println("=========完成注册信息======"); if(this.hasErrors()){ this.addActionError("输入的注册信息有误"); return INPUT; } return SUCCESS; } @Override public void validate() { if(null==user.getUsername() || "".equals(user.getUsername())){ this.addFieldError("user.username", "用户名不能为空!"); } if(null==user.getPassword() || "".equals(user.getPassword())){ this.addFieldError("user.password", "密码不能为空!"); } String ageStr="^\\d{1,3}$"; Pattern ageReg=Pattern.compile(ageStr); Matcher ageMatcher=ageReg.matcher(user.getAge()+""); if(!ageMatcher.matches()){ this.addFieldError("user.age", "年龄只能是数字,并只能为1-200之间!"); } if(null==user.getAge() || "".equals(user.getAge())){ this.addFieldError("user.age", "年龄不能为空!"); }else{ if(0>user.getAge() || 200<user.getAge()){ this.addFieldError("user.age", "年龄1-200之间!!"); } } String emaString="^\\[email protected]\\w+(.\\w{2,3}){1,2}$"; Pattern emailReg=Pattern.compile(emaString); Matcher emailMatcher=emailReg.matcher(user.getEmail()); if(!emailMatcher.matches()){ this.addFieldError("user.email", "邮箱格式不正确"); } super.validate(); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
如果Action中有validate()方法,会先执行验证,验证后才执行业务方法,不通过不执行业务方法
五、针对一个业务方法进行数据验证
使用validateXxx()方法
- Struts2支持validateXxx()方法针对xxx()方法进行数据验证
- 使用validateRegister()方法实现针对register()方法的数据验证
- 注册时通过validateRegister()方法验证年龄和邮箱等其它字段
- 注册和登录时在validate()方法中验证用户名和密码非空等其它验证
validate()方法和validateXxx()方法同时存在时都会起作用
ValidateXxx()方法的调用要先于validate()方法
5.1、使用针对注册的验证方法
package com.pb.web.action; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; import com.pb.entity.User; public class UserAction2 extends ActionSupport { private User user; public String register() throws Exception { System.out.println("=========完成注册信息======"); if(this.hasErrors()){ return INPUT; } return SUCCESS; } @Override public void validate() { System.out.println("====执行validate方法验证===="); if(null==user.getUsername() || "".equals(user.getUsername())){ this.addFieldError("user.username", "用户名不能为空!"); } if(null==user.getPassword() || "".equals(user.getPassword())){ this.addFieldError("user.password", "密码不能为空!"); } } public void validateRegister(){ System.out.println("====执行validateRegister方法验证===="); String ageStr="^\\d{1,3}$"; Pattern ageReg=Pattern.compile(ageStr); Matcher ageMatcher=ageReg.matcher(user.getAge()+""); if(!ageMatcher.matches()){ this.addFieldError("user.age", "年龄只能是数字,并只能为1-200之间!"); } if(null==user.getAge() || "".equals(user.getAge())){ this.addFieldError("user.age", "年龄不能为空!"); }else{ if(0>user.getAge() || 200<user.getAge()){ this.addFieldError("user.age", "年龄1-200之间!!"); } } String emaString="^\\[email protected]\\w+(.\\w{2,3}){1,2}$"; Pattern emailReg=Pattern.compile(emaString); Matcher emailMatcher=emailReg.matcher(user.getEmail()); if(!emailMatcher.matches()){ this.addFieldError("user.email", "邮箱格式不正确"); } } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
struts.xml
<action name="register2" class="com.pb.web.action.UserAction2" method="register"> <result name="input">/register2.jsp</result> <result name="success">/registerSuccess.jsp</result> </action>
5.2、三种方法
六、验证框架
6.1、实现
package com.pb.web.action; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; import com.pb.entity.User; public class UserAction3 extends ActionSupport { private User user; public String register() throws Exception { System.out.println("=========完成注册信息======"); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
UserAction3-validation.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> <validators> <!-- 用户名验证--> <field name="user.username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空!</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">4</param> <param name="maxLength">16</param> <param name="trim">true</param> <message>用户名必须为${minLength}至${maxLength}个字符!,当前为${user.username}</message> </field-validator> </field> <!--密码 --> <field name="user.password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>密码不能为空!</message> </field-validator> <field-validator type="stringlength"> <!--去掉前后的空格 --> <param name="trim">true</param> <param name="minLength">6</param> <param name="maxLength">20</param> <message>密码必须为${minLength}至${maxLength}个字符,当前为${user.password}</message> </field-validator> </field> <!--年龄 --> <field name="user.age"> <field-validator type="required"> <param name="trim">true</param> <message>年龄不能为空</message> </field-validator> <field-validator type="int"> <param name="trim">true</param> <param name="min">1</param> <param name="max">200</param> <message>年龄为${min}---${max}岁之间</message> </field-validator> </field> <field name="user.email"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>邮箱不能为空</message> </field-validator> <field-validator type="email"> <param name="trim">true</param> <message>邮箱格式不正确!</message> </field-validator> </field> </validators>
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册页面</title> </head> <body> <!-- 判断字段是否有错误信息--> <s:if test="hasFieldErrors()"> <h1 align="center">输出错误字段信息</h1> <div align="center" style="color:blue;"> 使用s:fielderror输出全部的错误信息 <s:fielderror /> </div> </s:if> <h1>ActionName-validation.xml较验</h1> <!-- 必须加上namespace不然不起作用--> <s:form action="register3.action" method="post" namespace="/" > <s:textfield label="用户名" name="user.username"/> <s:password label="密码" name="user.password"/> <s:textfield label="年龄" name="user.age" /> <s:textfield label="邮箱" name="user.email"/> <s:submit value="提交" /><s:reset value="重置" /><br/> </s:form> <s:debug/> </body> </html>
struts.xml
<action name="register3" class="com.pb.web.action.UserAction3" method="register"> <result name="input">/register3.jsp</result> <result name="success">/registerSuccess.jsp</result> </action>
七、针对一个业务编写配置文件
7.1、更改实现
将上面的年龄验证和邮箱验证独立出来
struts.xml
<action name="register3" class="com.pb.web.action.UserAction3" method="register"> <result name="input">/register3.jsp</result> <result name="success">/registerSuccess.jsp</result> </action>
UserAction3-validation.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> <validators> <!-- 用户名验证--> <field name="user.username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空!</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">4</param> <param name="maxLength">16</param> <param name="trim">true</param> <message>用户名必须为${minLength}至${maxLength}个字符!,当前为${user.username}</message> </field-validator> </field> <!--密码 --> <field name="user.password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>密码不能为空!</message> </field-validator> <field-validator type="stringlength"> <!--去掉前后的空格 --> <param name="trim">true</param> <param name="minLength">6</param> <param name="maxLength">20</param> <message>密码必须为${minLength}至${maxLength}个字符,当前为${user.password}</message> </field-validator> </field> </validators>
UserAction3-register3-validation.xml 中间的名称要与action名字相同
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> <validators> <!-- 用户名验证--> <field name="user.username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空!</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">4</param> <param name="maxLength">16</param> <param name="trim">true</param> <message>用户名必须为${minLength}至${maxLength}个字符!,当前为${user.username}</message> </field-validator> </field> <!--密码 --> <field name="user.password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>密码不能为空!</message> </field-validator> <field-validator type="stringlength"> <!--去掉前后的空格 --> <param name="trim">true</param> <param name="minLength">6</param> <param name="maxLength">20</param> <message>密码必须为${minLength}至${maxLength}个字符,当前为${user.password}</message> </field-validator> </field> </validators>
7.2、验证顺序
八、以上
时间: 2024-10-13 13:10:58