Struts2 自定义输入校验 第五弹
Struts2的校验框架有两种:一种是validate方法,另一种是有效的xml文件。
Action中自定义方法的输入校验,对于通过action的method属性所指定的自定义方法myExecute,其对应的自定义输入校验方法名为validateMyExecute(假设自定义的方法名为myExecute),底层是通过反射机制来调用的。
当在Action中制定了自定义的excute方法时,首先会执行自定义的excute方法所对应的输入校验方法,然后再去执行validate方法,执行完毕后如果出现了任何错误都不会再去执行自定义的excute方法,流程会转向了input这个返回结果的页面上面。
自定义Field级别的错误提示消息
1)新建一个以action命名的properties文件,如RegisterAction.properties
2)然后在该属性文件中指定每一个出错的字段的错误消息。指定方式:invalid.fieldvalue.具体属性 = 具体错误提示信息
--start 自定义方法的校验 ---
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>My JSP 'register.jsp' starting page</title> 14 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 <!-- 21 <link rel="stylesheet" type="text/css" href="styles.css"> 22 --> 23 24 </head> 25 26 <body> 27 <h2><font color="blue">用户注册</font></h2> 28 29 <s:actionerror cssStyle="color:red"/> 30 31 ---------------------------------------- 32 33 <s:fielderror cssStyle="color:blue"></s:fielderror> 34 35 <!-- 36 <form action="register.action"> 37 38 username: <input type="text" name="username" size="20"><br> 39 password: <input type="password" name="password" size="20"><br> 40 repassword: <input type="password" name="repassword" size="20"><br> 41 age: <input type="text" name="age" size="20"><br> 42 birthday: <input type="text" name="birthday" size="20"><br> 43 graduation: <input type="text" name="graduation" size="20"><br> 44 45 <input type="submit" value="submit"/> 46 47 </form> 48 --> 49 <s:form action="register.action" theme="simple"> 50 51 username: <s:textfield name="username" label="username"></s:textfield><br> 52 password: <s:password name="password" label="password"></s:password><br> 53 repassword: <s:password name="repassword" label="repassword"></s:password><br> 54 age: <s:textfield name="age" label="age"></s:textfield><br> 55 birthday: <s:textfield name="birthday" label="birthday"></s:textfield><br> 56 graduation: <s:textfield name="graduation" label="graduation"></s:textfield><br> 57 58 <s:submit value="submit"></s:submit> 59 </s:form> 60 61 </body> 62 </html>
<?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"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
1 import java.util.Date; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class RegisterAction extends ActionSupport 6 { 7 private String username; 8 9 private String password; 10 11 private String repassword; 12 13 private int age; 14 15 private Date birthday; 16 17 private Date graduation; 18 19 public String getUsername() 20 { 21 return username; 22 } 23 24 public void setUsername(String username) 25 { 26 this.username = username; 27 } 28 29 public String getPassword() 30 { 31 return password; 32 } 33 34 public void setPassword(String password) 35 { 36 this.password = password; 37 } 38 39 public String getRepassword() 40 { 41 return repassword; 42 } 43 44 public void setRepassword(String repassword) 45 { 46 this.repassword = repassword; 47 } 48 49 public int getAge() 50 { 51 return age; 52 } 53 54 public void setAge(int age) 55 { 56 this.age = age; 57 } 58 59 public Date getBirthday() 60 { 61 return birthday; 62 } 63 64 public void setBirthday(Date birthday) 65 { 66 this.birthday = birthday; 67 } 68 69 public Date getGraduation() 70 { 71 return graduation; 72 } 73 74 public void setGraduation(Date graduation) 75 { 76 this.graduation = graduation; 77 } 78 79 @Override 80 public String execute() throws Exception 81 { 82 System.out.println(this.birthday); 83 84 return SUCCESS; 85 } 86 87 public String myExecute() throws Exception 88 { 89 System.out.println("myExecute invoked!"); 90 91 return SUCCESS; 92 } 93 94 public void validateMyExecute() 95 { 96 System.out.println("validateMyExecute invoked!!"); 97 } 98 99 100 @Override 101 public void validate() 102 { 103 System.out.println("validate invoked!"); 104 } 105 // @Override 106 // public void validate() 107 // { 108 // if(null == username || username.length() < 4 || username.length() > 6) 109 // { 110 // this.addActionError("username invalid"); 111 // 112 // this.addFieldError("username", "\u7528\u6237\u540d\u4e0d\u5408\u6cd5"); 113 // } 114 // 115 // if(null == password || password.length() < 4 || password.length() > 6) 116 // { 117 // this.addActionError("password invalid"); 118 // } 119 // else if(null == repassword || repassword.length() < 4 || repassword.length() > 6) 120 // { 121 // this.addActionError("repassword invalid"); 122 // } 123 // else if(!password.equals(repassword)) 124 // { 125 // this.addActionError("the passwords not the same"); 126 // } 127 // 128 // if(age < 10 || age > 50) 129 // { 130 // this.addActionError("age invalid"); 131 // } 132 // 133 // if(null == birthday) 134 // { 135 // this.addActionError("birthday invalid"); 136 // } 137 // 138 // if(null == graduation) 139 // { 140 // this.addActionError("graduation invalid"); 141 // } 142 // 143 // if(null != birthday && null != graduation) 144 // { 145 // Calendar c1 = Calendar.getInstance(); 146 // c1.setTime(birthday); 147 // 148 // Calendar c2 = Calendar.getInstance(); 149 // c2.setTime(graduation); 150 // 151 // if(!c1.before(c2)) 152 // { 153 // this.addActionError("birthday should be before graduation"); 154 // } 155 // } 156 // 157 // //this.getFieldErrors().clear(); 158 // //this.getActionErrors().clear(); 159 // 160 //// this.clearActionErrors(); 161 //// this.clearFieldErrors(); 162 // 163 // System.out.println("invoked!!!"); 164 // } 165 166 }
<%@ page language="java" import="java.util.*" 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"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'registerResult.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> username: <s:property value="username"/><br> password: <s:property value="password"/><br> age:<s:property value="age"/><br> birthday:<s:property value="birthday"/><br> graduate:<s:property value="graduation"/> </body> </html>
--end 自定义方法的校验 ---
自带的validateFailed 消息 是不明确的,需要自行修改。可以通过自定义属性文件实现(RegisterAction.properties,需要和action同路径)
1 invalid.fieldvalue.age=\u5E74\u9F84\u4E0D\u5408\u6CD5\! 2 invalid.fieldvalue.birthday=\u751F\u65E5\u65E5\u671F\u4E0D\u5408\u6CD5 3 invalid.fieldvalue.graduation=\u6BD5\u4E1A\u65E5\u671F\u4E0D\u5408\u6CD5
其中,invalid.fieldvalue.age中的invalid.fieldvalue是固定的,不可修改。
如果提示中文的消息native2ascii.exe 是将中文转化为ASCII码(在jdk/bin目录下面,如果转化直接输入中文敲回车即可!)
第二种校验方法:有效的xml文件,具体分为字段优先的和校验器优先的
需要将***-validation.xml的文件放置在对应的action路径下面。
比如如果要验证RegisterAction,则需要命名为:RegisterAction-validation.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> 4 5 <validators> 6 <!-- 7 <field name="username"> 8 <field-validator type="requiredstring"> 9 <param name="trim">false</param> 10 <message>username can't be blank!</message> 11 </field-validator> 12 <field-validator type="stringlength"> 13 <param name="minLength">4</param> 14 <param name="maxLength">6</param> 15 <param name="trim">false</param> 16 <message key="username.invalid"></message> 17 </field-validator> 18 </field> 19 20 <field name="password"> 21 <field-validator type="requiredstring"> 22 <message>password can't be blank!</message> 23 </field-validator> 24 <field-validator type="stringlength"> 25 <param name="minLength">4</param> 26 <param name="maxLength">6</param> 27 <message>length of password should be between ${minLength} and ${maxLength}</message> 28 </field-validator> 29 </field> 30 31 <field name="age"> 32 <field-validator type="required"> 33 <message>age can't be blank!</message> 34 </field-validator> 35 <field-validator type="int"> 36 <param name="min">10</param> 37 <param name="max">40</param> 38 <message>age should be between ${min} and ${max}</message> 39 </field-validator> 40 41 </field> 42 43 <field name="birthday"> 44 <field-validator type="required"> 45 <message>birthday can't be blank!</message> 46 </field-validator> 47 <field-validator type="date"> 48 <param name="min">2005-1-1</param> 49 <param name="max">2007-12-31</param> 50 <message>birthday should be between ${min} and ${max}</message> 51 </field-validator> 52 </field> 53 54 --> 55 56 <validator type="requiredstring"> 57 <param name="fieldName">username</param> 58 <message>username can't be blank!</message> 59 </validator> 60 61 <validator type="stringlength"> 62 <param name="fieldName">username</param> 63 <param name="minLength">4</param> 64 <param name="maxLength">6</param> 65 <message>length of username should be between ${minLength} and ${maxLength}</message> 66 </validator> 67 68 <field name="birthday"> 69 <field-validator type="required"> 70 <message>birthday can't be blank!</message> 71 </field-validator> 72 <field-validator type="date"> 73 <param name="min">2005-1-1</param> 74 <param name="max">2007-12-31</param> 75 <message>birthday should be between ${min} and ${max}</message> 76 </field-validator> 77 </field> 78 </validators>