Struts2请求参数校验

时间:2023-03-08 17:04:42

校验的分类

  客户端数据校验 和 服务器端数据校验
  客户端数据校验 ,通过JavaScript 完成校验 (改善用户体验,使用户减少出错 )
  服务器数据校验 ,通过Java代码 完成校验

struts2 支持校验方式
  代码校验(用的很少) :在服务器端通过编写java代码,完成数据校验
  配置校验(主流):XML配置校验(主流) 和 注解配置校验
  代码校验请求参数
    步骤一: 封装数据
    步骤二: 实现校验Action ,必须继承ActionSupport 类
    步骤三: 覆盖validate方法(validate方法在请求处理方法execute之前执行!)通过代码逻辑判断参数是否有效,如果参数非法,用this.addFieldError(ActionSupport提供)存储校验错误信息,跳转回 input页面
    步骤四: 在jsp中 通过 <s:fieldError/>(打印所有错误信息)(或<s:fielderror fieldName="">(打印某个错误信息))显示错误信息
    validate方法会对Action中所有业务方法进行校验,如果只想校验某一个方法:用validate方法名()(例如validateRegist())

    示例:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="regist" class="com.yzu.RegistAction">
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

struts.xml

<%@ 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 '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">
<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>
<s:fielderror/>
<form action="${pageContext.request.contextPath}/regist" method="post">
username:<input type="text" name="username"><s:fielderror fieldName="username.message"/><br>
password:<input type="password" name="password"><s:fielderror fieldName="password.message"/><br>
<input type="submit" value="注册">
</form>
</body>
</html>

index.jsp

package com.yzu;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
//使用模型驱动
public class RegistAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
public User getModel() {
return user;
}
@Override
public String execute() throws Exception {
System.out.println("execute method.....");
return null;
}
@Override
public void validate() {
System.out.println(11);
if (user.getUsername() == null
|| user.getUsername().trim().length() == 0) {
// 说明用户名为空
this.addFieldError("username.message", "用户名不能为空");
}
if (user.getPassword() == null
|| user.getPassword().trim().length() == 0) {
this.addFieldError("password.message", "密码不能为空");
}
}
}

RegistAction

package com.yzu;

import java.util.Arrays;
import java.util.Date; public class User { private String username;
private String password;
private int age;
private Date birthday;
private String[] hobby; private String url;
private String email;
private String telphone; private String repassword; public String getRepassword() {
return repassword;
} public void setRepassword(String repassword) {
this.repassword = repassword;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getTelphone() {
return telphone;
} public void setTelphone(String telphone) {
this.telphone = telphone;
} public String[] getHobby() {
return hobby;
} public void setHobby(String[] hobby) {
this.hobby = hobby;
} 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Override
public String toString() {
return "User [username=" + username + ", password=" + password
+ ", age=" + age + ", birthday=" + birthday + ", hobby="
+ Arrays.toString(hobby) + "]";
} }

User

  Xml配置方式数据校验
    XML配置方式是主流校验的校验方式,代码校验不适用于大型项目,因为当流程数据复杂时,代码校验的开发量和维护量都会很大
    xml配置校验原理 :将很多校验规则代码已经写好,只需要在xml中定义数据所使用校验规则就可以了
    配置文件配置要求
      位置:xml文件要与action类在同一个包下
      名称:action类名-validation.xml
      约束: xwork-core-2.3.7.jar 中 xwork-validator-1.0.3.dtd 下

<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

      书写:
        1.根元素:<validators>
        2.子元素:<field name="属性名称"></field>
        3.<field>子元素 :<field-validator type="校验器"> 这个是指定校验器
          Struts2提供的校验器有如下这些(xwork-core-2.3.7.jar 中 /com/opensymphony/xwork2/validator/validators/default.xml下

<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"/>

        4.<field-validator>子元素:<message>错误信息</message>
        5.<field-validator>子元素:<param name="">值</param>用于指定校验器中的参数.
        内建校验器介绍

required (必填校验器,要求被校验的属性值不能为null)
requiredstring (必填字符串校验器,要求被校验的属性值不能为null,并且长度大于0,默认情况下会对字符串去前后空格)
stringlength (字符串长度校验器,要求被校验的属性值必须在指定的范围内,否则校验失败,minLength参数指定最小长度,maxLength参数指定最大长度,trim参数指定校验field之前是否去除字符串前后的空格)
regex (正则表达式校验器,检查被校验的属性值是否匹配一个正则表达式,expression参数指定正则表达式,caseSensitive参数指定进行正则表达式匹配时,是否区分大小写,默认值为true)
int(整数校验器,要求field的整数值必须在指定范围内,min指定最小值,max指定最大值)
double(双精度浮点数校验器,要求field的双精度浮点数必须在指定范围内,min指定最小值,max指定最大值)
fieldexpression (字段OGNL表达式校验器,要求field满足一个ognl表达式,expression参数指定ognl表达式,该逻辑表达式基于ValueStack进行求值,返回true时校验通过,否则不通过)
email(邮件地址校验器,要求如果被校验的属性值非空,则必须是合法的邮件地址)
url(网址校验器,要求如果被校验的属性值非空,则必须是合法的url地址)
date(日期校验器,要求field的日期值必须在指定范围内,min指定最小值,max指定最大值)

案例

<?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>
<!-- 对username属性进行校验 -->
<field name="username">
<!-- 指定username不能为空 -->
<field-validator type="requiredstring">
<!-- 错误信息 -->
<message>用户名不能为空--------</message>
</field-validator>
<!-- 长度校验,规定用户名必须在6-10位之间 -->
<field-validator type="stringlength">
<param name="maxLength">10</param>
<param name="minLength">6</param>
<message>用户名必须在${minLength}-${maxLength}位之间</message>
</field-validator>
</field> <!-- 对age进行校验,规定年龄必须在10-40之间 -->
<field name="age">
<field-validator type="int">
<param name="min">10</param>
<param name="max">40</param>
<message>年龄必须在${min}--${max}之间</message>
</field-validator>
</field> <!-- 对birthday进行校验 -->
<field name="birthday">
<field-validator type="date">
<param name="min">1974-01-01</param>
<param name="max">2004-12-31</param>
<message>生日必须在${min}年到${max}年之间</message>
</field-validator>
</field> <!-- 校验邮箱 -->
<field name="email">
<field-validator type="email">
<message>邮箱格式不正确</message>
</field-validator>
</field> <!-- url校验 --> <field name="url">
<field-validator type="url">
<message>url不能这空,类似于http://www.baidu.com</message>
</field-validator>
</field> <!-- 使用正则 -->
<field name="telphone">
<field-validator type="regex">
<param name="regexExpression"><![CDATA[^135[0-9]{8}$]]></param>
<message>电话号码必须是135xxxxxxxx</message>
</field-validator>
</field> <field name="repassword">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[(password==repassword)]]></param>
<message>两次密码输入不一致</message>
</field-validator>
</field> </validators>

UserAction-regist-validation.xml 

自定义校验规则(了解一下就行,实际开发中很少用到自定义校验器)
  步骤一: 自定义校验器 必须实现 Validator 接口
      通常自定义校验器 继承 ValidatorSupport 和 FieldValidatorSupport
        ValidatorSupport 针对不是一个输入字段 (两个密码一致)
        FieldValidatorSupport 针对是一个输入字段 (用户名非空)
  步骤二: 注册校验器
      在工程的src下新建validators.xml文件,引入 xwork-core-2.3.7.jar 中 xwork-validator-config-1.0.dtd
  步骤三 :使用校验器
      在Action所有包 创建Action类名-validation.xml