一.对所有方法进行校验
1.action继承ActionSuppor类,重写validate方法。
public class personAction extends ActionSupport{
/**通过代码方式对所有action进行校验
* test:对页面上的用户名称和用户密码进行有效性校验*/
private String telephone;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String save()
{
message = "保存成功";//如果校验不通过,不会执行这行语句,返回的result也不是"success",而是"input"
return "success" ;
}
@Override
public void validate() {
if(telephone == null || telephone.trim().equals(""))
{
this.addFieldError("telephoneNull", "手机号码为空");
}
else if(!Pattern.compile("^1[358]\\d{9}$").matcher(telephone).matches())
{
this.addFieldError("telephoneError", "手机号码不符合规范");
}
}
}
2.在.xml配置文件中配置如下信息
<!--通过代码对所有action进行有效性校验 -->
<action name = "validate_*" class = "com.action.personAction" method = "{1}">
<result name="input">/index.jsp</result>
<result name = "success">/WEB-INF/page/validate.jsp</result>
</action>
如果校验不通过,fieldErrors中存在校验失败信息,struts2会将请求转发到name为input的result。不提供input的result,如果有this.addFieldError("xxxError", "xxx")操作,程序会报:No result defined for action com.action.personAction and result input
3.jsp调用
<form action ="<%=request.getContextPath() %>/department/validate_save.action" method = "post">
电话号码:<input type = "text" name = "telephone"><br/>
<input type = "submit" value="提交">
</form>
二.对指定方法进行校验
不重写validate()方法,增加validateXxx方法,如validate
Save,指只针对save方法进行校验。主要方法名首字母大写。