struts_19_对Action中所有方法、某一个方法进行输入校验(手工编写代码实现输入校验)

对所有方法进行校验
1、通过手工编写代码的形式实现

需求:
用户名:不能为空
手机号:不能为空,并且要符合手机号的格式1,3/5/8,后面是9个数字

第01步:导包

第02步:配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
     <!-- 第00步:启动Struts框架 -->
    <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>
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

第03步:编写bean

package cn.itcast.bean;

/**
 * 第01步:
 * ******编写bean
 */
public class Person {
    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;
    }
}

第04步:编写action类

package cn.itcast.action;

import java.util.regex.Pattern;

import cn.itcast.bean.Person;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 第02步:
 * 编写action
 */
public class PersonAction extends ActionSupport{//需要继承ActionSupport类
    private Person person;
    
    /**第03步:编写action方法update()、save(),下一步:struts.xml**/
    /**3.1**/
    public String update(){
        System.out.println("执行update!");
        ActionContext.getContext().put("message", "更新成功");
        return "message";
    }
    /**3.2**/
    public String save(){
        System.out.println("执行save!");
        ActionContext.getContext().put("message", "保存成功");
        return "message";
    }
    /**3.3**/
    public String other(){
        System.out.println("执行other!");
        ActionContext.getContext().put("message", "other");
        return "message";
    }
    
    /**第05步:PersonAction继承ActionSupport,并编写校验方法;下一步:编写界面**/
    /**5.1**/
    public void validateSave() {//validate+Save:会对save()方法校验
        System.out.println("对save()方法进行校验");
        if(this.person.getName()==null || "".equals(this.person.getName().trim())){
            this.addFieldError("username", "用户名不能为空");
        }
        if(this.person.getMobile()==null || "".equals(this.person.getMobile().trim())){
            this.addFieldError("mobile", "手机号不能为空");
        }else{
            //调用校验Pattern类方法:不能为空,首个数字:1(^1),第二个数字:3、5、8([358],以任意9个数字:(\d{9}),结尾:($))1,3/5/8,后面是9个数字
            if(!Pattern.compile("^1[358]\d{9}$").matcher(this.person.getMobile()).matches()){
                this.addFieldError("mobile", "手机号格式不正确");
            }
        }
    }
    /**5.2**/
    public void validateUpdate() {//validate+Update:会对update()方法校验
        System.out.println("对update()方法进行校验");
        if(this.person.getName()==null || "".equals(this.person.getName().trim())){
            this.addFieldError("username", "用户名不能为空");
        }
        if(this.person.getMobile()==null || "".equals(this.person.getMobile().trim())){
            this.addFieldError("mobile", "手机号不能为空");
        }else{
            if(!Pattern.compile("^1[358]\d{9}$").matcher(this.person.getMobile()).matches()){
                this.addFieldError("mobile", "手机号格式不正确");
            }
        }
    }
    /**5.3**/
    public void validate() {//validate:会对所有action方法校验
        System.out.println("对所有action方法进行校验");
        if(this.person.getName()==null || "".equals(this.person.getName().trim())){
            this.addFieldError("username", "用户名不能为空");
        }
        if(this.person.getMobile()==null || "".equals(this.person.getMobile().trim())){
            this.addFieldError("mobile", "手机号不能为空");
        }else{
            if(!Pattern.compile("^1[358]\d{9}$").matcher(this.person.getMobile()).matches()){
                this.addFieldError("mobile", "手机号格式不正确");
            }
        }
    }
    
    /**set()、get()方法*/
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
    
}

第05步:配置struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>     
     <package name="person" namespace="/person" extends="struts-default">
            <action name="manage_*" class="cn.itcast.action.PersonAction" method="{1}">
<!-- 指定input出错时显示的视图 --> <result name="input">/index.jsp</result> <result name="message">/WEB-INF/page/message.jsp</result> </action> </package> </struts>

第06步:编写界面

index.jsp:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>输入校验</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0"> 
  </head>
  
  <body>
  save方法校验
      <!-- s:fielderror显示失败信息 -->
   <s:fielderror/>
   <form action="person/manage_save.action" method="post">
           用户名:<input type="text" name="person.name"/>不能为空<br/>
           手机号:<input type="text" name="person.mobile"/>不能为空,并且要符合手机号的格式1,3/5/8,后面是9个数字<br/>
           <input type="submit" value="提 交"/></form>

  update方法校验
   <s:fielderror/>
   <form action="person/manage_update.action" method="post">
           用户名:<input type="text" name="person.name"/>不能为空<br/>
           手机号:<input type="text" name="person.mobile"/>不能为空,并且要符合手机号的格式1,3/5/8,后面是9个数字<br/>
           <input type="submit" value="提 交"/></form>

   所有方法校验
   <s:fielderror/>
   <form action="person/manage_other.action" method="post">
           用户名:<input type="text" name="person.name"/>不能为空<br/>
           手机号:<input type="text" name="person.mobile"/>不能为空,并且要符合手机号的格式1,3/5/8,后面是9个数字<br/>
           <input type="submit" value="提 交"/></form>
  </body>
</html>
message.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>结果</title>
  </head>
  
  <body>
    ${message }
  </body>
</html>

实现流程:

1、浏览器提交请求
2、Struts2调用默认类型转换器,转换表单提交的值,将值付给action的属性:person
3、如果在转换类型的过程中出现异常,系统将异常保存到ActionContext。conversionError拦截器将异常信息封装到fieldErrors里。不管类型转换时否出现异常,都会进入第4步
4、通过反射技术,先调用action中的validateXxx()方法校验单个action方法(Xxx为action方法名,首字母大写)。如果出错,系统将错误信息保存到fieldErrors里
5、然后调用action中的方法validate()方法校验所有action方法。如果出错,系统将错误信息保存到fieldErrors里
6、如果出错(即fieldErrors存在信息,即存放的size大于0),请求自动转发到input视图(input视图会显示错误信息,和原提交界面信息)。如果没有错,系统执行action方法

 注意:

注意:
1、如果校验方法没错,任然转发到input视图,那么可能是转换器,转换时出错。因为转换错误信息会保存到fieldErrors里,校验错误信息也会保存到fieldErrors里面。比如添加一个Date(日期)类型,那么就会转换类型出错,转到input视图。
2、需要在struts中指定input出错时显示的视图
原文地址:https://www.cnblogs.com/zjsy/p/4364884.html