Struts2学习笔记(四) Action(中)

来源:互联网 发布:幼儿绘画软件 编辑:程序博客网 时间:2024/06/07 07:08

前面说道实现Action一般选择继承ActionSupport的方式,因为它提供了一些额外的功能,比如基本的数据验证和访问本地信息。

基本数据验证

由于ActionSupport类实现了Validateable接口,那么在该动作被触发的时候会在执行动作方法之前先执行validate方法,如果验证没有通过,那么就会返回信息输入结果页面。因此我们只需要在Action中重写validate方法就可以实现数据的验证了。

[java] view plaincopyprint?
  1. public class HelloWorld extends ActionSupport {  
  2.   
  3.     private String userName;  
  4.   
  5.   
  6.     public String getUserName() {  
  7.         return userName;  
  8.     }  
  9.   
  10.     public void setUserName(String userName) {  
  11.         this.userName = userName;  
  12.     }  
  13.   
  14.     public String execute1() throws Exception {  
  15.           
  16.           
  17.         return "success";  
  18.     }  
  19.   
  20.     @Override  
  21.     public void validate() {  
  22.         if(userName == null){  
  23.             addFieldError("userName","未获取到参数!");  
  24.         }else if(userName.length()>5){  
  25.             addFieldError("userName","用户名太长");  
  26.         }  
  27.           
  28.     }  
  29.   
  30. }  

input.jsp

<body>

  <s:if test="hasFieldErrors()">

    <s:iterator value="fieldErrors"> 

        <font color="#FF0000"><s:property value="value[0]"/></font><br> 

    </s:iterator> 

  </s:if>

 

  <form action="login.action" method="post">

     username : <input type="text" name="userName"/><br/>

     password :<input type="password" name="password"><br/>

      <input type="submit" value="submit"/>

  </form>

 

  </body>


执行:

结果:

这里有几点需要注意:

(1) 每次执行动作方法之前,都会执行validate方法,如果我们的Action中有多个动作方法的话,那么每个动作方法执行之前都会执行validate方法,因此validate方法中一般执行一些通用的检查。

(2)  如果validate中没有通过,即产生了错误消息,那么不会执行动作方法,会直接返回”input”。

下面大致了解一下validate方法执行的原理。首先我们需要知道,这个方法是被拦截器调用的,拦截器放在动作执行之前,拦截每个访问该Action的请求。这个拦截器叫做Workflow拦截器,查看文档可以知道,该拦截器的实现类为com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor。文档中说这个拦截器要做的事情:

(1)如果Action中有validate{MethodName}()方法,那么执行它

(2)如果(1)不成立,但是Action中有validateDo{MethodName}()方法,那么执行它

(3)不管(1)或(2)是否执行,只要这个拦截器的alwaysInvokeValidate属性为true,那么总是会执行validate方法。

查看DefaultWorkflowInterceptor的源码:

[java] view plaincopyprint?
  1. public class DefaultWorkflowInterceptor extends MethodFilterInterceptor {  
  2.   
  3.     private static final long serialVersionUID = 7563014655616490865L;  
  4.   
  5.     private static final Logger LOG = LoggerFactory.getLogger(DefaultWorkflowInterceptor.class);  
  6.   
  7.     private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];  
  8.       
  9. private String inputResultName = Action.INPUT;  
  10.   
  11.     public void setInputResultName(String inputResultName) {  
  12.         this.inputResultName = inputResultName;  
  13.     }  
  14.   
  15.     @Override  
  16.     protected String doIntercept(ActionInvocation invocation) throws Exception {  
  17.         Object action = invocation.getAction();  
  18.   
  19.         if (action instanceof ValidationAware) {  
  20.             ValidationAware validationAwareAction = (ValidationAware) action;  
  21.   
  22.             if (validationAwareAction.hasErrors()) {  
  23.                 if (LOG.isDebugEnabled()) {  
  24.                     LOG.debug("Errors on action " + validationAwareAction + ", returning result name 'input'");  
  25.                 }  
  26.   
  27.                 String resultName = inputResultName;  
  28.   
  29.                 if (action instanceof ValidationWorkflowAware) {  
  30.                     resultName = ((ValidationWorkflowAware) action).getInputResultName();  
  31.                 }  
  32.   
  33.                 InputConfig annotation = action.getClass().getMethod(invocation.getProxy().getMethod(), EMPTY_CLASS_ARRAY).getAnnotation(InputConfig.class);  
  34.                 if (annotation != null) {  
  35.                     if (!annotation.methodName().equals("")) {  
  36.                         Method method = action.getClass().getMethod(annotation.methodName());  
  37.                         resultName = (String) method.invoke(action);  
  38.                     } else {  
  39.                         resultName = annotation.resultName();  
  40.                     }  
  41.                 }  
  42.   
  43.   
  44.                 return resultName;  
  45.             }  
  46.         }  
  47.   
  48.         return invocation.invoke();  
  49.     }  
  50.   
  51. }  

发现在这个拦截器中根本就没有调用validate方法,而只是对是否产生的错误信息进行了检测。并且看以看到,如果存在错误信息,默认返回的Result是Action.input(”input”)。

那么既然workflow拦截器没有执行validate方法,由于我们的Action使用的默认的拦截器栈,那么就去看看在workflow拦截器前面的拦截器validation拦截器。

查看文档可以知道这个拦截器的实现类为:org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor。这个类继承了com.opensymphony.xwork2.validator.ValidationInterceptor这个类查看这个类的源码,里面有一个doBeforInvocation方法:

[java] view plaincopyprint?
  1. protected void doBeforeInvocation(ActionInvocation invocation) throws Exception {  
  2.         Object action = invocation.getAction();  
  3.         ActionProxy proxy = invocation.getProxy();  
  4.   
  5.         //the action name has to be from the url, otherwise validators that use aliases, like  
  6.         //MyActio-someaction-validator.xml will not be found, see WW-3194  
  7.         String context = proxy.getActionName();  
  8.         String method = proxy.getMethod();  
  9.   
  10.         if (log.isDebugEnabled()) {  
  11.             log.debug("Validating "  
  12.                     + invocation.getProxy().getNamespace() + "/" + invocation.getProxy().getActionName() + " with method "+ method +".");  
  13.         }  
  14.           
  15.   
  16.         if (declarative) {  
  17.            if (validateAnnotatedMethodOnly) {  
  18.                actionValidatorManager.validate(action, context, method);  
  19.            } else {  
  20.                actionValidatorManager.validate(action, context);  
  21.            }  
  22.        }      
  23.           
  24.         if (action instanceof Validateable && programmatic) {  
  25.             // keep exception that might occured in validateXXX or validateDoXXX  
  26.             Exception exception = null;   
  27.               
  28.             Validateable validateable = (Validateable) action;  
  29.             if (LOG.isDebugEnabled()) {  
  30.                 LOG.debug("Invoking validate() on action "+validateable);  
  31.             }  
  32.               
  33.             try {  
  34.                 PrefixMethodInvocationUtil.invokePrefixMethod(  
  35.                                 invocation,   
  36.                                 new String[] { VALIDATE_PREFIX, ALT_VALIDATE_PREFIX });  
  37.             }  
  38.             catch(Exception e) {  
  39.                 // If any exception occurred while doing reflection, we want   
  40.                 // validate() to be executed  
  41.                 if (LOG.isWarnEnabled()) {  
  42.                     LOG.warn("an exception occured while executing the prefix method", e);  
  43.                 }  
  44.                 exception = e;  
  45.             }  
  46.               
  47.               
  48.             if (alwaysInvokeValidate) {  
  49.                 validateable.validate();  
  50.             }  
  51.               
  52.             if (exception != null) {   
  53.                 // rethrow if something is wrong while doing validateXXX / validateDoXXX   
  54.                 throw exception;  
  55.             }  
  56.         }  
  57.     }  

可以看到,正是在这个方法中对Action中的validate方法进行了调用。为了验证到底validate方法是在validation拦截器中被调用的还是在workflow拦截器中被调用的,我们写个小实例,不使用defaultStack,我们手动为Action配置拦截器栈(这个拦截器栈基本和defaultStack相同):

[html] view plaincopyprint?
  1. <package name="default" namespace="/" extends="struts-default">  
  2.           
  3.         <interceptors>  
  4.             <interceptor-stack name="luo">  
  5.                 <interceptor-ref name="exception"/>  
  6.                 <interceptor-ref name="alias"/>  
  7.                 <interceptor-ref name="servletConfig"/>  
  8.                 <interceptor-ref name="i18n"/>  
  9.                 <interceptor-ref name="prepare"/>  
  10.                 <interceptor-ref name="chain"/>  
  11.                 <interceptor-ref name="scopedModelDriven"/>  
  12.                 <interceptor-ref name="modelDriven"/>  
  13.                 <interceptor-ref name="fileUpload"/>  
  14.                 <interceptor-ref name="checkbox"/>  
  15.                 <interceptor-ref name="multiselect"/>  
  16.                 <interceptor-ref name="staticParams"/>  
  17.                 <interceptor-ref name="actionMappingParams"/>  
  18.                 <interceptor-ref name="params">  
  19.                   <param name="excludeParams">dojo\..*,^struts\..*</param>  
  20.                 </interceptor-ref>  
  21.                 <interceptor-ref name="conversionError"/>  
  22.                  
  23.                 <interceptor-ref name="workflow">  
  24.                     <param name="excludeMethods">input,back,cancel,browse</param>  
  25.                 </interceptor-ref>  
  26.                 <interceptor-ref name="debugging"/>  
  27.                   
  28.             </interceptor-stack>  
  29.         </interceptors>     
  30.         <default-interceptor-ref name="luo"></default-action-ref>  
  31.         <action name="hello" class="action.HelloWorld">  
  32.             <result name="success">/success.jsp</result>  
  33.             <result name="input">/input.jsp</result>  
  34.         </action>  
  35.   
  36.     </package>  

我们仅仅是将validation拦截器移出了Action的先前默认的defaultStack拦截器栈中,我们再来执行前面执行过的测试:

结果:

success结果被显示了,说明validate方法没有被调用了。那么就说明了validate方法是在validattion拦截器中被调用的。

workflow拦截器和validation拦截器可以传递一些参数:

[html] view plaincopyprint?
  1. <interceptor-ref name="validation">  
  2.       <paramnameparamname="excludeMethods">input,back,cancel,browse</param>  
  3. </interceptor-ref>  

当执行到与excludeMethods参数中指定的方法同名的方法时,拦截器不会做出反映。还可以通过这种形式来为拦截器指定其他属性,比如为workflow指定默认返回的Result等。

[html] view plaincopyprint?
  1. <interceptor-ref name="workflow">  
  2.        <param name="inputResultName">error</param>  
  3.        <param name="excludeMethods">*</param>  
  4.        <param name="includeMethods">myWorkflowMethod</param>  
  5. </interceptor-ref>  

访问本地信息

在上面的例子程序中,我们将错误信息硬编码在代码中,这样有一些弊端:

(1)       一是不容易修改,如果我们想改变消息的内容,还得重新修改代码和重新编译类

(2)       而是不利于国际化,如果要将其中的中文换成英文,那么还得到代码中来修改和重新编译类

通过访问本地信息,我们将一些消息按照键值对的形式保存在类文件外部的文件,通过key来获取文件中对应的消息,那么一旦我们需要修改消息内容,那么就只需要修改这个外部文件而不需要重新编译类了。基本步骤:

(1)       首先建立消息文件,在Action类的类路径下建立一个与Action同名的properties文件,例如HelloWorld.properties,然后在文件里按照 key= value的形式添加错误消息。

nameIsNull =\u672A\u83B7\u53D6\u5230\u53C2\u6570

nameIsTooLong=\u7528\u6237\u540D\u592A\u957F

需要注意的是Value的值必须是unicode编码,这样在程序充才能正确获取,在eclipse中可以使用可视化工具编辑properties文件,这样生成的代码会将中文转换为unicode编码。JDK中也提供了native2ascii命令来实现这种转换,具体方法google一下就知道了。

(2)修改原来在Actin中硬编码的错误消息,改成从配置文件中读取信息。

public void validate() {

   if(userName ==null){

      addFieldError("userName",getText("nameIsNull"));

   }else if(userName.length()>5){

     addFieldError("userName",getText("nameIsTooLong"));

   }

}

重新运行程序,结果和前面一样。至于实现的原理,最终还是借助JDK提供的ResourceBoundle来实现的。ActionSupport类实现了TextProvider接口和LocalProvider接口。当我们调用ActionSupport的getText方法时,其内部实际上是调用了TextProvider一个实现类(TextProviderSupport)的对象上的getText方法。

public String getText(String aTextName) {

        return getTextProvider().getText(aTextName);

}

 

private TextProvider getTextProvider() {

       if (textProvider ==null) {

           TextProviderFactory tpf = new TextProviderFactory();

           if (container !=null) {

                container.inject(tpf);

           }

          textProvider = tpf.createInstance(getClass(), this);

       }

       return textProvider;

 }

由于实现了LocalProvider,因此ActionSupport也是LocalProvider类型,其getLocal从ActionContext中获取Local对象。使用系统默认的Local对象时,ResourceBoundle会在Class所在路径下寻找与当前类同名的properties文件,如果使用指定的Local对象,那么我们的资源文件还需要在名字中添加相应的国家代码,例如:HelloWorld_zh_CN.properties

0 0
原创粉丝点击