struts2 基础4

Posted Mr·Liu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2 基础4相关的知识,希望对你有一定的参考价值。

验证器:

验证器:用户输入验证
 1.手动编程方式
      1)对于动作类中所有方法进行验证
            a.动作类继承ActionSuport
            b.覆盖调用public void validate(){} 方法
            c.在validate方法中,编写不符合要求的代码判断,并调用父类的addFieldError(String fieldName,String errorMessage)
                如果fieldError(存放错误信息的Map)有任何的元素,就是验证不通过,动作方法不会执行。
                Struts2框架会返回到name=input的result
            d.在name=input指定的页面上使用struts2的标签显示错误信息。<s:fielderror />
            
        2)对于动作类中指定方法进行验证 
              编写步骤与手动编程方式相同,验证方法书写要求如下:
              public void validate[Add]() { } //检测add()方法
 1 package cn.gs.ly;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 
 5 public class UserAction extends ActionSupport {
 6     private String username;  //不能为空
 7     private String password;  //不能为空 ,切三到六位数字
 8     
 9     public String getUsername() {
10         return username;
11     }
12     public void setUsername(String username) {
13         this.username = username;
14     }
15     public String getPassword() {
16         return password;
17     }
18     public void setPassword(String password) {
19         this.password = password;
20     }
21     
22     
23     
24     public String add(){
25         System.out.println("add方法执行成功");
26         return SUCCESS;
27     }    
28     
29     
30     public String update(){
31         System.out.println("update方法执行成功");
32         return SUCCESS;
33     }
34     
35     @Override
36     //对于动作类中所有方法进行验证
37     public void validate() { //只验证不符合条件的数据
38         if(username==null||"".equals(username.trim())){
39             addFieldError("username", "姓名不能为空");
40         }
41         if(password==null||!password.matches("\\d{3,6}")){
42             addFieldError("password", "密码不能为空,切为3-6位纯数字");
43         }
44     }
45     
46 //    //对于动作类中指定方法进行验证
47 //    public void validateAdd() { //只验证不符合条件的数据
48 //        if(username==null||"".equals(username.trim())){
49 //            addFieldError("username", "姓名不能为空");
50 //        }
51 //        if(password==null||!password.matches("\\d{3,6}")){
52 //            addFieldError("password", "密码不能为空,切为3-6位纯数字");
53 //        }
54 //    }
55     
56 }

  2、基于XML配置文件的方式:

    1、对于动作类中所有方法进行验证:  UserAction-validation.xml
            在动作类中的包中建立一个名称为:动作类简单名-validation.xml
            
    2、对于动作类中指定方法进行验证:  UserAction-user_add-validation.xml
            动作类简单名-action名-validation.xml
 1 默认验证器:    
 2     <validators>
 3         <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
 4         <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
 5         <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
 6         <validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
 7         <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
 8         <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
 9         <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
10         <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
11         <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
12         <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
13         <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
14         <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
15         <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
16         <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
17         <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
18         <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
19     </validators>

  具体配置方法示例:

    对于动作类中所有方法进行验证: UserAction-validation.xml

    对于动作类中指定方法进行验证: UserAction-user_add-validation.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2  <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">    
 5 <struts>
 6     <constant name="struts.devMode" value="true"></constant>
 7     <constant name="struts.i18n.encoding" value="UTF-8"></constant>    
 8     <constant name="struts.custom.i18n.resources" value="GS"></constant>
 9 
10     <package name="mypackage" extends="struts-default">            
11         <global-results><!-- 全局错误页 -->
12             <result name="error" type="dispatcher">/customer/error.jsp</result>
13         </global-results>
14     </package>
15     
16     <package name="validate" namespace="/validate" extends="struts-default">
17         <action name="user_*" class="cn.gs.ly.UserAction" method="{1}">
18             <result type="dispatcher" name="success">/success.jsp</result>
19             <result type="dispatcher" name="error">/error.jsp</result>
20             <result type="dispatcher" name="input">/{1}User.jsp</result>  <!-- 转换数据类型失败,输入验证错误 -->
21         </action>
22     </package>
23 </struts>

  3、自定义验证器

    1.编写一个类,继承FieldValidatorSupport类
    2.重写 public void validate(Object object) throws ValidationException {} 方法,编写逻辑
    3.注册验证器
        在WEB-INF/classes目录下(src)建立一个validators.xml 配置文件。

    <validators>
      <validator name="strongpassword" class="cn.gs.ly.validators.StrongPasswordValidator"/>
    </validators>

实例
1
package cn.gs.ly.validators; 2 3 import com.opensymphony.xwork2.validator.ValidationException; 4 import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport; 5 6 public class StrongPasswordValidator extends FieldValidatorSupport { 7 8 public void validate(Object object) throws ValidationException { 9 String fieldName = getFieldName();//取得字段名 10 String filedValue = (String)getFieldValue(fieldName, object);//取得用户输入的当前字段的值 11 if(!isPasswordStrong(filedValue)){ 12 addFieldError(fieldName, object); 13 } 14 } 15 private static final String GROUP1 = "abcdefghijklmnopqrstuvwxyz"; 16 private static final String GROUP2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 17 private static final String GROUP3 = "0123456789"; 18 protected boolean isPasswordStrong(String password) { 19 boolean ok1 = false; 20 boolean ok2 = false; 21 boolean ok3 = false; 22 int length = password.length(); 23 for(int i=0;i<length;i++){ 24 if(ok1&&ok2&&ok3) 25 break; 26 String character = password.substring(i,i+1); 27 if(GROUP1.contains(character)){ 28 ok1 = true; 29 continue; 30 } 31 if(GROUP2.contains(character)){ 32 ok2 = true; 33 continue; 34 } 35 if(GROUP3.contains(character)){ 36 ok3 = true; 37 continue; 38 } 39 } 40 return ok1&&ok2&&ok3; 41 } 42 }

  4、Struts2对于i18n的支持

    命名规则:
        basename.properties
        basename_language_country.properties
        basename_language.properties
    1.全局范围
            在WEB-INF/classes目录下
    2.包范围
      服务于Java类中的包下的动作类的。
      取名:package_语言_国家.properties package_
**_.properties 3.action范围
      放到与动作类相同的包中
      取名:动作类名_语言_国家.properties actionclass_
**_.properties

文件内容
1 GS_zh_CN.properties:
2     welcome={0}   \u6B22\u8FCE\u6765\u5230\u8FD9\u91CC."i18n test"  {1}
3     
4 GS_en_US.properties:
5     welcome={0}   welcome to here."i18n test"  {1}

  4.1、jsp中读取国际化的消息:

 1 <%@ page language="java" contentType="text/html" pageEncoding="utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags" %>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <s:text name="welcome"> 
11         <s:param >刘超</s:param>  <!-- 给welcome添加赋值于占位符处({*}) -->
12         <s:param >go home</s:param>
13     </s:text>
14         
15     <s:i18n name="cn/gs/ly/package">  <!-- 包范围 -->
16         <s:text name="welcome"> 
17             <s:param >刘超</s:param>  
18             <s:param >go home</s:param>
19         </s:text>
20     </s:i18n>
21 </body>
22 </html>

  4.2、动作类中读取国际化的消息

 1 package cn.gs.ly;
 2 
 3 import com.opensymphony.xwork2.ActionContext;
 4 import com.opensymphony.xwork2.ActionSupport;
 5 
 6 public class I18nAction extends ActionSupport {
 7     
 8     @Override
 9     public String execute() throws Exception {
10         //String value = getText("welcome"); //获取welcome 对应的值
11         
12         //获取welcome 对应的值 ,并添加赋值于占位符({*})处
13         String value = getText("welcome",new String[]{"LY","good brother"});
14         
15         ActionContext.getContext().put("message", value);        
16         return SUCCESS;
17     }
18 }

 










以上是关于struts2 基础4的主要内容,如果未能解决你的问题,请参考以下文章

Struts2基础01

Struts2入门

[vscode]--HTML代码片段(基础版,reactvuejquery)

struts2+springmvc+hibernate开发。个人纪录

struts2请求过程源代码分析

SSH框架简化(struts2+spring+hibernate)