Struts数据效验
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts数据效验相关的知识,希望对你有一定的参考价值。
表单数据的验证:
前台验证:主要是通过JS验证, 表达数据是否合法!
后台验证:通过后台java代码进行验证!
Struts也提供了数据效验的方式!
Struts数据效验, 通过拦截器完成:
<interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
代码方式验证Action中所有的方法:
步骤:
1. 搭建struts环境
2. login.jsp
3.UserAction.java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP ‘index.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"> <!-- 修改struts标签默认的样式: 不让换行 <style type="text/css"> ul{ display: inline; } ul li{ display: inline; color: red; } </style> --> </head> <body> <%@taglib uri="/struts-tags" prefix="s" %> <br/> <form method="post" action="${pageContext.request.contextPath }/vuser_register"> 用户名:<input type="text" name="user.userName"> <s:fielderror fieldName="user.userName"></s:fielderror> <br/> 密码:<input type="text" name="user.pwd"> <s:fielderror fieldName="user.pwd"></s:fielderror> <br/> 邮箱:<input type="text" name="user.email"><br/> 生日:<input type="text" name="user.birth"><br/> <input type="submit" value="注册"><br/> </form> </body> </html>
User类
package com.gqx.validate; import java.util.Date; public class User { private String userName; private String pwd; private String email; private Date birth; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "User [birth=" + birth + ", email=" + email + ", pwd=" + pwd + ", userName=" + userName + "]"; } }
UserAction.java
package com.gqx.validate; import com.opensymphony.xwork2.ActionSupport; /** * 注意:如果要想用struts的数据效验功能,必须继承ActionSupport或实现相关接口 * @author GQXing * */ public class UserAction extends ActionSupport{ //封装数据 private User user=new User(); public void setUser(User user) { this.user = user; } public User getUser() { return user; } @Override public void validate() { // 用户名非空 if (user.getUserName() == null || "".equals(user.getUserName())) { // 保存错误信息 super.addFieldError("userName", "用户名必须填写!"); } // 密码 if (user.getPwd() == null || "".equals(user.getPwd())) { super.addFieldError("pwd", "密码必填"); } } // 业务方法 public String register() { System.out.println(user); return SUCCESS; } // 列表展示(不用数据效验) public String list() { return SUCCESS; } }
也可以对指定方法进行验证,如只对register方法验证,而不对list方法验证
package com.gqx.validate; import com.opensymphony.xwork2.ActionSupport; /** * 注意:如果要想用struts的数据效验功能,必须继承ActionSupport或实现相关接口 * @author GQXing * */ public class UserAction extends ActionSupport{ //封装数据 private User user=new User(); public void setUser(User user) { this.user = user; } public User getUser() { return user; } public void validateRegister() { // 用户名非空 if (user.getUserName() == null || "".equals(user.getUserName())) { // 保存错误信息 super.addFieldError("userName", "用户名必须填写!"); } // 密码 if (user.getPwd() == null || "".equals(user.getPwd())) { super.addFieldError("pwd", "密码必填"); } } // 业务方法 public String register() { System.out.println(user); return SUCCESS; } // 列表展示(不用数据效验) public String list() { return SUCCESS; } }
XML方式验证Action中所有的方法:
繁琐,设计很多重复的验证逻辑!例如:非空验证、数值验证、email、日期等。
Struts对于常用的验证,进行了封装,即提供了验证器, 验证指定的常用业务逻辑!
Struts提供的所有验证器——路径:xwork-core-2.3.4.1.jar/com.opensymphony.xwork2.validator.validators/default.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator Definition 1.0//EN" "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd"> <!-- START SNIPPET: validators-default --> <validators> <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/> <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> <validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/> <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/> <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/> <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/> <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/> <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/> <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/> <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/> <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> </validators> <!-- END SNIPPET: validators-default -->
如果写xml,从而定义验证规则:
1)XML文件名称语法: ActionClassName-validation.xml
注意:此xml需要与当期要验证的action在同一个目录:
举例:UserAction-validation.xml
2) 写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> <!-- 验证Email --> <field name="user.email"> <field-validator type="email"> <message>邮箱格式错误!</message> </field-validator> </field> <!-- 验证的每一个字段用field表示 --> <field name="user.userName"> <!-- 指定使用的验证器 --> <field-validator type="requiredstring"> <!-- 验证失败的错误提示信息 --> <message>用户名不能为空!</message> </field-validator> </field> <!-- 验证pwd --> <field name="user.pwd"> <!-- 非空 --> <field-validator type="requiredstring"> <message>密码不能为空!</message> </field-validator> <!-- 长度 --> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">8</param> <message>密码必须为6-8位!</message> </field-validator> </field> <!-- 验证日期 --> <field name="user.birth"> <field-validator type="date"> <message>日期格式不对!</message> </field-validator> </field> </validators>
XML方式验证Action中指定的方法:
与上面xml验证方式大致相同: 验证xml文件内容不变;
文件命名:
语法:ActionClassName-ActionName-validation.xml
举例:UserAction-user_register-validation.xml
验证UserAction中的register方法
验证总结
代码:
重写validate() , 验证action所有方法
Validate方法名(), 验证指定“方法名”的方法
Xml:
验证所有方法: ActionClassName-validation.xml
验证指定方法: ActionClassName-actionName-validation.xml
代码验证,
比较灵活,可以满足所有的需求.
比较繁琐,要写重复的验证判断逻辑!
适合: 表单字段较少的情况用!
XML验证:
通用,但不够灵活; 可以验证特定简单的业务。
适合: 验证表单字段较多,可以大大简化代码!
(配置文件过多)
以上是关于Struts数据效验的主要内容,如果未能解决你的问题,请参考以下文章