对Action指定方法进行校验
手工编写代码实现对action指定方法输入校验:
通过validateXxx()方法实现,validateXxx只会校验action中方法名为Xxx的方法。其中Xxx的第一个字母要大写。
code:
index.jsp:
package cn.itcast.action;import java.util.regex.Pattern;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class PersonAction extends ActionSupport{/** * @author wangfeng */private static final long serialVersionUID = 6609644196829871636L;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";}//will validate the "update" functionpublic void validateUpdate(){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", "手机号格式不正确");}}}}