Struts 2チェックの手動チェック

3072 ワード

簡単な実用的な方法:対応する処理論理方法xxxの前にvalidateを加えればよい.例えばadd方法の検証方法名はvalidateAddである.
   実行順序、validateAdd--->validate----->add
例:
1,Action
package com.supan.action;
import com.opensymphony.xwork2.ActionSupport;
public class ValidatorAction extends ActionSupport {
	private String name;
    private int    age;
    private String address;
    public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
    public void validate() {
    	System.out.println("validator        ");
    	super.validate();
    }
    @Override
    public String execute() throws Exception {
    	// TODO Auto-generated method stub
    	return super.execute();
    }
    //       validate    
    public void validateAdd(){
    	System.out.println("     add   ");
    	if(!getName().contains("   ")){
    		addFieldError("   ", "              ");
    		addActionError("         ");
    	}
    	if(getAge() <= 0 || getAge() >= 120){
    		addFieldError("  ", "      0,  120 ");
    		addActionError("         ");
    	}
    	if(getAddress().length() < 10){
    		addFieldError("  ", "         ");
    		addActionError("         ");
    	}
    }
    public String add(){
    	return SUCCESS;
    }
}

2,struts構成
<action name="addTest" class="com.supan.action.ValidatorAction" method="add">
             <result name="success">/validator.jsp</result>
             <result name="input">/validator.jsp</result>
</action>

3,ページ:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s"  uri="/struts-tags"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
      <s:fielderror></s:fielderror>
      <s:form action="addTest">
         <s:textfield name="name" label="  "></s:textfield>
         <s:textfield name="age" label="  "></s:textfield>
         <s:textfield name="address" label="  "></s:textfield>
         <s:submit value="  "></s:submit>
      </s:form>      
  </body>
</html>