Struts2的Action中自定义方法的输入校验

Terwer Struts2评论148字数 1182阅读3分56秒阅读模式

自定义方法的输入校验

  1. 对于通过 action​ 的 method​ 属性所指定的自定义方法 myExecute​ ,其对应的自定义输入校验方法名为 validateMyExecute​ 。 (底层是通过反射调用的)
    public void validateMyExecute() {
    System.out.println("validateMyExecute invoked");
    
     this.addActionError("action error");
    }
    
    public String myExecute() throws Exception {
    System.out.println("myExecute invoked");
    return SUCCESS;
    }
    
  2. 校验方法的执行顺序

    当在 Action​ 中指定了自定义的 execute​ 方法时,首先会执行自定义的 execute​ 方法所对应的输入校验方法,然后再去执行 validate​ 方法,执行完毕之后如果出现了任何错误都不会再去执行自定义的 execute​ 方法,流程转向了 input​ 这个名字所对应的页面上。文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

    public void validateMyExecute() {
    System.out.println("validateMyExecute invoked");
    
     this.addActionError("action error");
    }
    
    @Override
    public void validate() {
    System.out.println("validate invoked");
    
    // this.addActionError("action error");
    }
    
    @Override
    public String execute() throws Exception {
    return SUCCESS;
    }
    
    public String myExecute() throws Exception {
    System.out.println("myExecute invoked");
    return SUCCESS;
    }
    // validateMyExecute invoked
    // validate invoked
    

    效果文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

    Struts2的Action中自定义方法的输入校验文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

自定义 Field 级别的校验信息

在 Action 的同级目录新建一个属性文件,例如:RegisterAction.properties文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

invalid.fieldvalue.birthday=age invalid custom msg
invalid.fieldvalue.graduation=graduation invalid custom msg

结果如下:文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

Struts2的Action中自定义方法的输入校验文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

总结:文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

  1. 新建一个以 Action​ 名命名的 properties 文件,如: RegisterAction.properties
  2. 然后在该属性文件中指定每一个出错字段的错误消息,格式:
    invalid.fieldvalue.borthday=birthday invalid custom msg
    

文章源自浅海拾贝-https://blog.terwergreen.com/the-input-verification-of-the-custom-method-in-the-action-method-in-struts2-zuo2wb.html

相关文章
  • 扫码加我微信
  • 验证消息请输入:来自你的博客
  • weinxin
  • 我的微信公众号
  • 微信扫一扫与我交流吧
  • weinxin
Terwer
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: