Struts2中验证表单数据(使用声明式验证)

1. struts.xml 配置

<?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>
    <constant name="struts.devMode" value="true"></constant>
    <package name="p1" extends="struts-default">
        <!-- 声明式验证器案例的动作类配置 -->
        <action name="addStudent" class="com.ljq.web.action.StudentAction" method="addStudent" >           
            <result name="input">/student.jsp</result>  <!-- 验证失败时,请求参数带回 -->
            <result>/success.jsp</result> <!-- 默认name=“success” -->
        </action>
    </package>
</struts>

 

2. POJO类 (Plain Ordinary Java Object 简单的Java对象,实际就是普通JavaBeans)

package com.ljq.domain;

import java.io.Serializable;
/**
 * URL: uniform resource locator 统一资源定位符
 * http://localhost:8080/day25_ee19_05struts2convert/register.jsp
 * 协议             主机                 端口        URI    
 * URI: uniform resource identifier 统一资源标识符
 * /day25_ee19_05struts2convert/register.jsp
 * @author zhy
 *
 */
public class Student implements Serializable {
    private String username;//不能为null和空字符串。要去空格
    private int age;//整数,介于18-100之间
    private String email;//按照邮箱的格式输入
    private String password;//密码,长度是3~8位
    private String repassword;//确认密码,必须和密码一致。写在这的目的,完全是为了演示验证器的使用。实际开发中根本不会保存确认密码
    private int score;//成绩,必须是自然数
    private String url;//个人主页:必须符合url格式。
    private String gender;//性别
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRepassword() {
        return repassword;
    }
    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    
    
}
View Code

 

3. Action类

package com.ljq.web.action;

import com.ljq.domain.Student;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class StudentAction extends ActionSupport implements ModelDriven<Student> {

    Student stu = new Student();

    @Override
    public Student getModel() {
        return stu;
    }
    
    //动作方法
    public String addStudent(){
        return SUCCESS;
    }

    public Student getStu() {
        return stu;
    }

    public void setStu(Student stu) {
        this.stu = stu;
    }

}

 

4. 验证配置文件 StudentAction-addStudent-validation.xml ,放在Action类所在的包下。写了该配置文件,就要在struts.xml 中配置 <result name="input"> 标签,否则报错(No result defined for action.....and result input

命名规范:Action类名 -  ActionName(struts.xml中的action name)-validation.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">
<!-- 当使用ActionClassName-validation.xml来命名文件时,它是一个动作类验证器。会验证动作类中的所有动作方法,  同样可以使用 @SkipValidate 跳过验证-->
<!-- 当使用ActionClassName-ActionName-validation.xml来命名文件时,它是一个指定动作方法的验证器。只会验证指定的动作方法 -->
<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>请输入用户名</message>
        </field-validator>
    </field>
    
    <field name="age">
        <field-validator type="int">
            <!-- 使用注入的方式,设置最大和最小值 -->
            <param name="min">18</param>
            <param name="max">100</param>
            <message>请输入18-100之间的整数</message>
        </field-validator>
    </field>
    
    <field name="email">
        <field-validator type="email">
            <message>请输入正确的邮箱格式</message>
        </field-validator>
    </field>
    
    <field name="password">
        <field-validator type="requiredstring">
            <!-- 注入取消使用trim -->
            <param name="trim">false</param>
            <message>请输入密码</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="minLength">3</param>
            <param name="maxLength">8</param>
            <message>密码长度是3~8位的</message>
        </field-validator>
    </field>

    <!-- 确认密码和密码必须保持一致,是2个字段的事,所以要使用基于验证器的声明方式 -->
    <validator type="expression">
        <param name="expression">
            <![CDATA[
                password == repassword
            ]]>
        </param>
        <message>两次密码必须一致</message>
    </validator>
    
    <field name="score">
        <field-validator type="regex">
            <param name="regex">
                \d+
            </param>
            <message>请输出正确的成绩</message>
        </field-validator>
    </field>
    
    <field name="url">
        <field-validator type="url">
            <message>请输入正确的url地址</message>
        </field-validator>
    </field>
    
    <field name="gender">
        <!-- required是一个只验证是否null的内置验证器,不会去除空格 -->
        <field-validator type="required">
            <message>请选择性别</message>
        </field-validator>
    </field>
</validators>

 5. student.jsp 显示

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%--导入struts2的标签库 --%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户注册,使用的是struts2的标签</title>
    <s:head></s:head>
  </head>
  <body>
      <s:actionerror/> <%--动作错误 --%>
      <%--<s:fielderror /> 字段错误 --%>
      <%--struts2的form标签,它提供了和原始html表单标签几乎一致的属性
          action:请求的地址。直接写动作名称。不用写contextPaht
          method:请求的方式。在这里不用写。struts2的form表单默认就是post
          enctype:表单编码的MIME类型
      --%>
      <s:form action="addStudent.action">
          <s:textfield name="username" label="用户名" />
          <s:textfield name="age" label="年龄"/>
          <s:textfield name="email" label="邮箱"/>
          <s:textfield name="password" label="密码" />
          <s:textfield name="repassword" label="确认密码"/>
          <s:textfield name="score" label="成绩"/>
          <s:textfield name="url" label="个人主页"/>
          <%--list中的取值是生成一个list集合,并往集合中放入元素 --%>
          <s:radio name="gender" list="{'男','女'}"  label="性别"/>
          <s:submit value="注册"/>
      </s:form>
  </body>
</html>

 

posted @ 2020-08-08 15:51  htj10  阅读(233)  评论(0编辑  收藏  举报
TOP