struts2示例代碼-對Action所有方法或指定方法校驗(手寫方法)

1.首先在類裏先繼承extends ActionSupport

2.HelloWordAction裏的方法

package cn.itcast.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.regex.Pattern;

public class HelloWordAction extends ActionSupport {
    private String username;
    private String tel;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String a(){
        ActionContext.getContext().put("aa", "aaaaaa");
        return "success";
    }
    public String b(){
        ActionContext.getContext().put("aa", "bbbbbbb");
        return "success";
    }
    public void validate() {  //重寫validate方法麼,會對所有的Action方法校驗
        if(this.username==null||this.username.equals("")){
            this.addFieldError("username", "用戶名不能爲空"); //addFieldError是輸出校驗錯誤信息
        }
        if(this.tel==null||this.tel.equals("")){
            this.addFieldError("tel", "電話不能爲空");
        }
        else{
            if(!Pattern.compile("^1[358]\\d{9}$").matcher(this.tel).matches()){ //Pattern.compile(正則表達式).matcher(匹配輸出字段).matches()
                this.addFieldError("tel", "手機號格式不正確");
            }
            
        }
        super.validate();
    }
    

}

3.輸出校驗信息,通過input視圖

struts.xml:

<result name="input" >/index.jsp</result>

需要用到struts標籤

index.jsp

<%@ taglib uri="/struts-tags" prefix="s"%>

  <s:fielderror/>


如果需要指定方法進行校驗只需要將

 public void validate(){}中的validate改成validate方法名稱,其中方法名稱的第一個字母大寫,例如 public void validateAdd(){}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章