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(){}