struts2提交数据校验

 通过重写validate()方法实现,validate()方法会校验action中所有与execute方法签名相同的方法。

当某个数据校验失败时,应调用addFieldError()方法往系统的fieldErrors添加失败信息,因此action需要继承ActionSupport()。

如果系统的fieldErrors包含失败信息,sturts2会将请求转发到名为input的result。

在input视图中可以通过<s:fielderror/>显示失败信息。

 

一、对Action中指定方法执行校验

二、对Action中全局方法执行校验

 

1、局部校验

public class PersonAction extends ActionSupport{
    private String username;
    private String mobile;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    
    public String update(){
        ActionContext.getContext().put("message", "更新成功");
        return "message";
    }
    
    public String save(){
        ActionContext.getContext().put("message", "保存成功");
        return "message";
    }
    
    public void validateUpdate() {//会对update()方法校验
        if(this.username==null || "".equals(this.username.trim())){
            this.addFieldError("username", "用户名不能为空");
        }
        if(this.mobile==null || "".equals(this.mobile.trim())){
            this.addFieldError("mobile", "手机号不能为空");
        }else{
            if(!Pattern.compile("^1[358]\\d{9}$").matcher(this.mobile).matches()){
                this.addFieldError("mobile", "手机号格式不正确");
            }
        }
    }
    
}

 

2、全局校验

public class PersonAction extends ActionSupport{
    private String username;
    private String mobile;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    
    public String update(){
        ActionContext.getContext().put("message", "更新成功");
        return "message";
    }
    
    public String save(){
        ActionContext.getContext().put("message", "保存成功");
        return "message";
    }
    
    @Override
    public void validate() {//会对action中的所有方法校验
        if(this.username==null || "".equals(this.username.trim())){
            this.addFieldError("username", "用户名不能为空");
        }
        if(this.mobile==null || "".equals(this.mobile.trim())){
            this.addFieldError("mobile", "手机号不能为空");
        }else{
            if(!Pattern.compile("^1[358]\\d{9}$").matcher(this.mobile).matches()){
                this.addFieldError("mobile", "手机号格式不正确");
            }
        }
    }
    
}

 

posted @ 2015-10-11 19:34  W&L  阅读(161)  评论(0编辑  收藏  举报