(七)Struts2 验证框架
所有的学习我们必须先搭建好Struts2的环境(1、导入对应的jar包,2、web.xml,3、struts.xml)
第一节:Struts2 验证简介
Struts2 基于Struts2 拦截器,为开发者提供了一套易用的验证框架,并可扩展;一般的验证都支持。
第二节:Struts2 内置验证
一,普通字段验证
二,验证表达式:
<s:actionerror/>(在配置信息中最后“用户名和真实姓名不能相同”的话,即表明有error,所以用表达式,在前端页面会有显示)
例子:
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 8 <package name="manager" extends="struts-default"> 9 10 <action name="registerAction" class="com.wishwzp.action.RegisterAction"> 11 <result name="input">/register.jsp</result> 12 <result name="success">/success.jsp</result> 13 </action> 14 15 </package> 16 17 </struts>
User.java
1 package com.wishwzp.model; 2 3 public class User { 4 5 private String userName;//用户名 6 private String name;//真实姓名 7 private int age;//年龄 8 private String email;//邮件 9 private String homePage;//主页 10 11 public String getUserName() { 12 return userName; 13 } 14 public void setUserName(String userName) { 15 this.userName = userName; 16 } 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 public int getAge() { 24 return age; 25 } 26 public void setAge(int age) { 27 this.age = age; 28 } 29 public String getEmail() { 30 return email; 31 } 32 public void setEmail(String email) { 33 this.email = email; 34 } 35 public String getHomePage() { 36 return homePage; 37 } 38 public void setHomePage(String homePage) { 39 this.homePage = homePage; 40 } 41 @Override 42 public String toString() { 43 return "User [userName=" + userName + ", name=" + name + ", age=" + age 44 + ", email=" + email + ", homePage=" + homePage + "]"; 45 } 46 47 48 }
RegisterAction.java
1 package com.wishwzp.action; 2 3 import com.wishwzp.model.User; 4 import com.opensymphony.xwork2.ActionSupport; 5 6 public class RegisterAction extends ActionSupport{ 7 8 /** 9 * 10 */ 11 private static final long serialVersionUID = 1L; 12 13 private User user; 14 15 public User getUser() { 16 return user; 17 } 18 19 public void setUser(User user) { 20 this.user = user; 21 } 22 23 @Override 24 public String execute() throws Exception { 25 System.out.println("传入的用户:"+user); 26 return SUCCESS; 27 } 28 29 30 31 }
RegisterAction-validation.xml (这个文件命名规范:XXXX-validation.xml,其中XXXX就是后台action类)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> 3 4 <validators> 5 6 <!-- 用户名格式验证 --> 7 <field name="user.userName"> 8 <field-validator type="requiredstring"> 9 <message>请输入用户名</message> 10 </field-validator> 11 <field-validator type="stringlength"> 12 <param name="minLength">6</param> 13 <param name="maxLength">10</param> 14 <message>用户名必须在${minLength}和${maxLength}之间</message> 15 </field-validator> 16 </field> 17 18 <!-- 真实姓名格式验证 --> 19 <field name="user.name"> 20 <field-validator type="requiredstring"> 21 <message>请输入姓名</message> 22 </field-validator> 23 </field> 24 25 <!-- 年龄格式验证 --> 26 <field name="user.age"> 27 <field-validator type="int"> 28 <param name="min">18</param> 29 <message>年龄必须满18周岁</message> 30 </field-validator> 31 </field> 32 33 <!-- 邮件格式验证 --> 34 <field name="user.email"> 35 <field-validator type="requiredstring"> 36 <message>请输入邮件</message> 37 </field-validator> 38 <field-validator type="email"> 39 <message>邮件格式不对</message> 40 </field-validator> 41 </field> 42 43 <!-- 主页格式验证 --> 44 <field name="user.homePage"> 45 <field-validator type="requiredstring"> 46 <message>请输入主页</message> 47 </field-validator> 48 <field-validator type="url"> 49 <message>主页格式不对</message> 50 </field-validator> 51 </field> 52 53 <!-- 用户名和真实姓名不能相同验证 --> 54 <!-- !user.name.equals(user.userName) 用户名和真实姓名不能相等,如果相等就是错误的信息,前端页面会有"<s:actionerror>"表达式显示错误信息 --> 55 <validator type="expression"> 56 <param name="expression"><![CDATA[!user.name.equals(user.userName)]]></param> 57 <message>用户名和真实姓名不能相同</message> 58 </validator> 59 </validators>
register.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="s" uri="/struts-tags" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 12 <!-- 这是就是用户名和真实姓名错误后显示的信息 --> 13 <s:actionerror/> 14 15 用户注册 16 <s:form action="/registerAction" method="post"> 17 <s:textfield name="user.userName" label="用户名"></s:textfield> 18 <s:textfield name="user.name" label="真实姓名"></s:textfield> 19 <s:textfield name="user.age" label="年龄"></s:textfield> 20 <s:textfield name="user.email" label="邮件"></s:textfield> 21 <s:textfield name="user.homePage" label="主页"></s:textfield> 22 <s:submit value="注册"></s:submit> 23 </s:form> 24 </body> 25 </html>
success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="s" uri="/struts-tags" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 注册成功 12 </body> 13 </html>
结果显示:(什么都没有写就提交了的结果显示)
第三节:自定义验证
例子:
validators.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE validators PUBLIC 3 "-//Apache Struts//XWork Validator Config 1.0//EN" 4 "http://struts.apache.org/dtds/xwork-validator-config-1.0.dtd"> 5 <validators> 6 <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> 7 <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/> 8 <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> 9 <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> 10 <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/> 11 <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> 12 <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> 13 <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/> 14 <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/> 15 <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/> 16 <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/> 17 <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/> 18 <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> 19 <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> 20 21 <!-- 自己定义配置的validatiors验证敏感词汇 --> 22 <validator name="sensitive" class="com.wishwzp.validators.SensitiveWordValidators"/> 23 </validators>
SensitiveWordValidators.java
1 package com.wishwzp.validators; 2 3 import com.opensymphony.xwork2.validator.ValidationException; 4 import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport; 5 6 public class SensitiveWordValidators extends FieldValidatorSupport{ 7 8 @Override 9 public void validate(Object object) throws ValidationException { 10 String fieldName=this.getFieldName();//获取字段名称 11 String value=this.getFieldValue(fieldName, object).toString();//获取用户输入的值 12 if(!check(value)){ 13 this.addFieldError(fieldName, object); 14 } 15 } 16 17 public boolean check(String value){ 18 String sensitiveWords[]={"你妹","你妈"};//敏感词汇 19 for(int i=0;i<sensitiveWords.length;i++){ 20 if(value.indexOf(sensitiveWords[i])>-1){ 21 return false; 22 } 23 } 24 return true; 25 } 26 27 }
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 6 <struts> 7 8 <package name="manager" extends="struts-default"> 9 10 <action name="validationAction" class="com.wishwzp.action.ValidationAction"> 11 <result name="input">/validation.jsp</result> 12 <result name="success">/success.jsp</result> 13 </action> 14 15 </package> 16 17 </struts>
ValidationAction.java
1 package com.wishwzp.action; 2 3 import com.wishwzp.model.User; 4 import com.opensymphony.xwork2.ActionSupport; 5 6 public class ValidationAction extends ActionSupport{ 7 8 /** 9 * 10 */ 11 private static final long serialVersionUID = 1L; 12 13 private String name; 14 15 16 17 public String getName() { 18 return name; 19 } 20 21 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 28 29 @Override 30 public String execute() throws Exception { 31 System.out.println("姓名:"+name); 32 return SUCCESS; 33 } 34 35 36 37 }
ValidationAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> 3 4 <validators> 5 <field name="name"> 6 <field-validator type="requiredstring"> 7 <message>请输入姓名</message> 8 </field-validator> 9 10 <field-validator type="sensitive"> 11 <message>有敏感词汇</message> 12 </field-validator> 13 </field> 14 15 </validators>
validation.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="s" uri="/struts-tags" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 简单自定义验证 12 <s:form action="/validationAction" method="post"> 13 <s:textfield name="name" label="姓名"></s:textfield> 14 <s:submit value="提交"></s:submit> 15 </s:form> 16 </body> 17 </html>
结果:
如果输入敏感词提交的话:
如果输入不是敏感词提交的话: