验证器:
验证器:用户输入验证
1.手动编程方式
1)对于动作类中所有方法进行验证 a.动作类继承ActionSuport b.覆盖调用public void validate(){} 方法 c.在validate方法中,编写不符合要求的代码判断,并调用父类的addFieldError(String fieldName,String errorMessage) 如果fieldError(存放错误信息的Map)有任何的元素,就是验证不通过,动作方法不会执行。 Struts2框架会返回到name=input的result d.在name=input指定的页面上使用struts2的标签显示错误信息。<s:fielderror /> 2)对于动作类中指定方法进行验证 编写步骤与手动编程方式相同,验证方法书写要求如下: public void validate[Add]() { } //检测add()方法
UserAction.java
1 package cn.gs.ly; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class UserAction extends ActionSupport { 6 private String username; //不能为空 7 private String password; //不能为空 ,切三到六位数字 8 9 public String getUsername() { 10 return username; 11 } 12 public void setUsername(String username) { 13 this.username = username; 14 } 15 public String getPassword() { 16 return password; 17 } 18 public void setPassword(String password) { 19 this.password = password; 20 } 21 22 23 24 public String add(){ 25 System.out.println("add方法执行成功"); 26 return SUCCESS; 27 } 28 29 30 public String update(){ 31 System.out.println("update方法执行成功"); 32 return SUCCESS; 33 } 34 35 @Override 36 //对于动作类中所有方法进行验证 37 public void validate() { //只验证不符合条件的数据 38 if(username==null||"".equals(username.trim())){ 39 addFieldError("username", "姓名不能为空"); 40 } 41 if(password==null||!password.matches("\d{3,6}")){ 42 addFieldError("password", "密码不能为空,切为3-6位纯数字"); 43 } 44 } 45 46 // //对于动作类中指定方法进行验证 对add()方法进行验证 47 // public void validateAdd() { //只验证不符合条件的数据 48 // if(username==null||"".equals(username.trim())){ 49 // addFieldError("username", "姓名不能为空"); 50 // } 51 // if(password==null||!password.matches("\d{3,6}")){ 52 // addFieldError("password", "密码不能为空,切为3-6位纯数字"); 53 // } 54 // } 55 56 }
struts.xml
<package name="validate" namespace="/validate" extends="struts-default">
<action name="user_*" class="cn.gs.ly.UserAction" method="{1}">
<result type="dispatcher" name="success">/success.jsp</result>
<result type="dispatcher" name="error">/error.jsp</result>
<result type="dispatcher" name="input">/{1}User.jsp</result> <!-- 转换数据类型失败,输入验证错误 -->
</action>
</package>
2、基于XML配置文件的方式:
1、对于动作类中所有方法进行验证: UserAction-validation.xml 在动作类中的包中建立一个名称为:动作类简单名-validation.xml 2、对于动作类中指定方法进行验证: UserAction-user_add-validation.xml 动作类简单名-action名-validation.xml
1 默认验证器: 2 <validators> 3 <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> 4 <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/> 5 <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> 6 <validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/> 7 <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/> 8 <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> 9 <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/> 10 <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> 11 <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> 12 <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/> 13 <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/> 14 <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/> 15 <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/> 16 <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/> 17 <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> 18 <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> 19 </validators>
具体配置方法示例:
UserAction.java
1 package cn.gs.ly; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class UserAction extends ActionSupport { 6 private String username; //不能为空 7 private String password; //不能为空 ,切三到六位数字 8 9 public String getUsername() { 10 return username; 11 } 12 public void setUsername(String username) { 13 this.username = username; 14 } 15 public String getPassword() { 16 return password; 17 } 18 public void setPassword(String password) { 19 this.password = password; 20 } 21 22 23 24 public String add(){ 25 System.out.println("add方法执行成功"); 26 return SUCCESS; 27 } 28 29 30 public String update(){ 31 System.out.println("update方法执行成功"); 32 return SUCCESS; 33 } 34 }
UserAction-validation.xml
在动作类中的包中建立一个名称为:动作类简单名-validation.xml
对于动作类中所有方法进行验证: UserAction-validation.xml
对于动作类中指定方法进行验证: UserAction-user_add-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE validators PUBLIC 3 "-//Apache Struts//XWork Validator 1.0.3//EN" 4 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> 5 6 <validators> 7 <field name="username"> 8 <field-validator type="requiredstring" > 9 <message>姓名不能为空哦。。。</message> 10 </field-validator> 11 </field> 12 13 <field name="password"> 14 <field-validator type="requiredstring"> 15 <message>密码不能为空哦。。。</message> 16 </field-validator> 17 <field-validator type="regex"> 18 <param name="regex"><![CDATA[(d{3,6})]]></param> 19 <message>密码为3-6位纯数字</message> 20 </field-validator> 21 </field> 22 23 </validators>
struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <constant name="struts.devMode" value="true"></constant> 7 <constant name="struts.i18n.encoding" value="UTF-8"></constant> 8 <constant name="struts.custom.i18n.resources" value="GS"></constant> 9 10 <package name="mypackage" extends="struts-default"> 11 <global-results><!-- 全局错误页 --> 12 <result name="error" type="dispatcher">/customer/error.jsp</result> 13 </global-results> 14 </package> 15 16 <package name="validate" namespace="/validate" extends="struts-default"> 17 <action name="user_*" class="cn.gs.ly.UserAction" method="{1}"> 18 <result type="dispatcher" name="success">/success.jsp</result> 19 <result type="dispatcher" name="error">/error.jsp</result> 20 <result type="dispatcher" name="input">/{1}User.jsp</result> <!-- 转换数据类型失败,输入验证错误 --> 21 </action> 22 </package> 23 </struts>
addUser.jsp
1 <%@ page language="java" contentType="text/html" pageEncoding="utf-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <s:fielderror fieldName="username"></s:fielderror> 11 <s:fielderror fieldName="password"></s:fielderror> 12 <form action="${pageContext.request.contextPath }/validate/user_add" method="post" > 13 姓名<input type="text" name="username"> <br> 14 密码<input type="text" name="password"> <br> 15 16 <input type="submit" value="保存"> 17 </form> 18 19 </body> 20 </html>
3、自定义验证器
自定义验证器 1.编写一个类,继承FieldValidatorSupport类 2.重写 public void validate(Object object) throws ValidationException {} 方法,编写逻辑 3.注册验证器 在WEB-INF/classes目录下(src)建立一个validators.xml 配置文件。详情参照 /com/opensymphony/xwork2/validator/validators/default.xml
UserAction.java
1 package cn.gs.ly.validators; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class UserAction extends ActionSupport { 6 7 private String password; 8 public String getPassword() { 9 return password; 10 } 11 public void setPassword(String password) { 12 this.password = password; 13 } 14 15 16 @Override 17 public String execute() throws Exception { 18 System.out.println("执行自定义验证器"); 19 return SUCCESS; 20 } 21 22 }
StrongPasswordValidator.java 编写逻辑
1.编写一个类,继承FieldValidatorSupport类
2.重写 public void validate(Object object) throws ValidationException {} 方法,编写逻辑
1 package cn.gs.ly.validators; 2 3 import com.opensymphony.xwork2.validator.ValidationException; 4 import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport; 5 //1.编写一个类,继承FieldValidatorSupport类 6 public class StrongPasswordValidator extends FieldValidatorSupport { 7 8 //2.重写 public void validate(Object object) throws ValidationException {} 方法,编写逻辑 9 public void validate(Object object) throws ValidationException { 10 String fieldName = getFieldName(); 11 String filedValue = (String)getFieldValue(fieldName, object); 12 13 System.out.print(fieldName+"=");System.out.println(filedValue); 14 15 if(!isPasswordStrong(filedValue)){ 16 addFieldError(fieldName, object); 17 } 18 } 19 20 21 private static final String GROUP1 = "abcdefghijklmnopqrstuvwxyz"; 22 private static final String GROUP2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 23 private static final String GROUP3 = "0123456789"; 24 25 protected boolean isPasswordStrong(String password) { 26 System.out.println("进入isPasswordString 方法,password:"+password); 27 boolean ok1 = false; 28 boolean ok2 = false; 29 boolean ok3 = false; 30 int length = password.length(); 31 32 for(int i=0;i<length;i++){ 33 if(ok1&&ok2&&ok3){ 34 break; 35 } 36 37 String character = password.substring(i,i+1); 38 if(GROUP1.contains(character)){ 39 ok1 = true; 40 continue; 41 } 42 if(GROUP2.contains(character)){ 43 ok2 = true; 44 continue; 45 } 46 if(GROUP3.contains(character)){ 47 ok3 = true; 48 continue; 49 } 50 } 51 return ok1&&ok2&&ok3; 52 } 53 }
validators.xml
3.注册验证器
在WEB-INF/classes目录下(src)建立一个validators.xml 配置文件。详情参照
/com/opensymphony/xwork2/validator/validators/default.xml 写法
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC
3 "-//Apache Struts//XWork Validator Definition 1.0//EN"
4 "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">
5
6 <validators>
7 <validator name="strongpassword" class="cn.gs.ly.validators.StrongPasswordValidator"/>
8 </validators>
UserAction-validation.xml 调用自定义的验证器
在动作类中的包中建立一个名称为:动作类简单名-validation.xml 使用验证器
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC
3 "-//Apache Struts//XWork Validator 1.0.3//EN"
4 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
5
6 <validators>
7
8 <field name="password">
9 <field-validator type="strongpassword">
10 <message>密码过于简单。请使用数字,大小写字母混合密码</message>
11 </field-validator>
12 </field>
13
14 </validators>
15
struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <constant name="struts.devMode" value="true"></constant> 7 <constant name="struts.i18n.encoding" value="UTF-8"></constant> 8 <constant name="struts.custom.i18n.resources" value="GS"></constant> 9 10 <package name="mypackage" extends="struts-default"> 11 <global-results><!-- 全局错误页 --> 12 <result name="error" type="dispatcher">/customer/error.jsp</result> 13 </global-results> 14 </package> 15 16 <package name="strongpassword" namespace="/strongpassword" extends="struts-default"> 17 <action name="isPasswordStrong" class="cn.gs.ly.validators.UserAction" > 18 <result type="dispatcher" name="success">/success.jsp</result> 19 <result type="dispatcher" name="error">/error.jsp</result> 20 <result type="dispatcher" name="input">/isPasswordStrong.jsp</result> 21 </action> 22 </package> 23 24 </struts>
isPasswordStrong.jsp
1 <%@ page language="java" contentType="text/html" pageEncoding="utf-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <s:fielderror fieldName="password"></s:fielderror> 11 12 <form action="${pageContext.request.contextPath }/strongpassword/isPasswordStrong" method="post" > 13 密码<input type="text" name="password"> <br> 14 <input type="submit" value="保存"> 15 </form> 16 </body> 17 </html>
4、Struts2对于i18n的支持
命名规则:
basename.properties
basename_language_country.properties
basename_language.properties
1.全局范围
在WEB-INF/classes目录下
2.包范围
服务于Java类中的包下的动作类的。
取名:package_语言_国家.properties
package_**_.properties
3.action范围
放到与动作类相同的包中
取名:动作类名_语言_国家.properties
actionclass_**_.properties
文件内容 1 GS_zh_CN.properties: 2 welcome={0} u6B22u8FCEu6765u5230u8FD9u91CC."i18n test" {1} 3 4 GS_en_US.properties: 5 welcome={0} welcome to here."i18n test" {1}
4.1、jsp中读取国际化的消息:
1 <%@ page language="java" contentType="text/html" pageEncoding="utf-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <s:text name="welcome"> 11 <s:param >刘超</s:param> <!-- 给welcome添加赋值于占位符处({*}) --> 12 <s:param >go home</s:param> 13 </s:text> 14 15 <s:i18n name="cn/gs/ly/package"> <!-- 包范围 --> 16 <s:text name="welcome"> 17 <s:param >刘超</s:param> 18 <s:param >go home</s:param> 19 </s:text> 20 </s:i18n> 21 </body> 22 </html>
4.2、动作类中读取国际化的消息
1 package cn.gs.ly; 2 3 import com.opensymphony.xwork2.ActionContext; 4 import com.opensymphony.xwork2.ActionSupport; 5 6 public class I18nAction extends ActionSupport { 7 8 @Override 9 public String execute() throws Exception { 10 //String value = getText("welcome"); //获取welcome 对应的值 11 12 //获取welcome 对应的值 ,并添加赋值于占位符({*})处 13 String value = getText("welcome",new String[]{"LY","good brother"}); 14 15 ActionContext.getContext().put("message", value); 16 return SUCCESS; 17 } 18 }
表格 隔行换色
1 <%@ page language="java" contentType="text/html" pageEncoding="utf-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <s:set var="list1" value="{'a','b','c'}"></s:set> 11 <table border="1" width="70%"> 12 <tr> 13 <th>姓名</th> 14 <th>性别</th> 15 <th>婚否</th> 16 </tr> 17 <s:iterator value="#list1" status="vs"> 18 <tr bgcolor="${vs.index%2==0?"green":"grey" }"> 19 <td>空格</td> 20 <td>空格</td> 21 <td>空格</td> 22 </tr> 23 </s:iterator> 24 </table> 25 26 </body> 27 </html>