struts2-数据验证

版权声明: https://blog.csdn.net/qq_34866380/article/details/79768815

数据验证分前后端,这里是struts提供的服务端数据验证,这个验证是在action方法执行之前进行的。
struts2中的validator配置在com.opensymphony.xwork2.validator.validators文件下,可进行调用。

struts2实现数据验证有两种方式:

一、手工编写代码实现
1、action继承actionSupport,重写validate()

public class testAction extends ActionSupport {
    private String name;
    private String mobile;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String execute(){    
        System.out.println("doFirst");
        return "success";
    }

    @Override
    public void validate() {
        if(name == null || "".equals(name)){
            this.addFieldError("age", "不能为空");
        }
        if(mobile == null || "".equals(mobile)){
            this.addFieldError("mobile", "不能为空");
        }else if (!Pattern.matches("^1[34578]\\d{9}$", mobile)) {
            this.addFieldError("mobile", "格式错误");
        }
        super.validate();
    }
}

2、表单页面(用struts-tags中的< s:fielderror>显示表单验证错误)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<s:fielderror></s:fielderror>
<form action="test/some" method="post">
    mobile : <input name="mobile" type="text"><br>
    name:   <input name="name" type="text"><br>
       <input type="submit" value="submit">
</form>
</body>
</html>

当action中有多个执行方法时,可通过在validate后加上执行方法名(首字母大写),即可让validate只在访问该方法前执行。

二、xml配置实现
在要进行验证操作action所在包,新建Action类名-validation.xml, xml的约束在struts2-core-2.5.14.1.jar/xwork-validator-1.0.3.dtd

<?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>
    <field name="name">
       <field-validator type="requiredstring"><!-- 验证器配置 -->
<!--           <param name="trim">true</param> -->
          <message>不能为空</message>
       </field-validator>
    </field>
    <field name="mobile">
       <field-validator type="requiredstring">
          <message>不能为空</message>
       </field-validator>
       <field-validator type="regex">
          <param name="regex"><![CDATA[^1[34578]\d{9}$]]></param><!-- 条件参数-->
          <message>格式错误</message>
       </field-validator>
    </field>
 </validators>

当action中有多个执行方法时,指定方法执行,重命名文件为:Action类名-struts.xml中action.name-validation.xml


总结Action执行流程:
类型转换->set值->数据验证->action方法

猜你喜欢

转载自blog.csdn.net/qq_34866380/article/details/79768815