Struts2中的“验证”之编程式验证

 
1)验证分为:编程式验证、声明式验证。
 
2)“验证”要用到的拦截器:
class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
 
3)实现Action有3种方式,即-->1.pojo;2.实现Action接口;3.继承ActionSupport类
一般我们会选择第三种方式--继承ActionSupport类,而这个ActionSupport类已经实现了Validateable、ValidationAware等接口。
 
4)编程式验证
验证步骤:
  <1>重写了Validateable中的validate()方法
<2>ValidationAware中含有方法--》addFieldError(String fieldName,String errorMessage) -->字 段名,错误提示
例:
①用户登录验证
public class UserAction extends ActionSupport implements ModelDriven {
  private User user = new User();
  public User getModel() {
    return this.user;
  }
  @Override
  public void validate() {
    if (this.user.getUname().length()==0) {
      this.addFieldError("uname", "用户名不能为空aaa!");
      this.addFieldError("uname", "用户名不能为空bbb!");  
      
    }
    super.validate();
  }
  public String execute() {
    return  this.success;
  }
}
 
②struts.xml中的配置:
 
 
③在jsp页面中显示错误信息-->2种方式
<1>使用struts2的表单,会默认自行添加到相应位置,不用自己再进行操作
注意:theme主题不能为simple
<2>


 
 
原文地址:https://www.cnblogs.com/gxpblogs/p/3072173.html