zoukankan      html  css  js  c++  java
  • Struts2中action接收参数的三种方法及ModelDriven和Preparable接口结合JAVA反射机制的灵活用法

    Struts2中Action接收参数的方法主要有以下三种:

    1.使用Action的属性接收参数(最原始的方式):
        a.定义:在Action类中定义属性,创建get和set方法;
        b.接收:通过属性接收参数,如:userName;
        c.发送:使用属性名传递参数,如:user1!add?userName=jim;
    2.使用DomainModel接收参数:
        a.定义:定义Model类,在Action中定义Model类的对象(不需要new),创建该对象的get和set方法;
        b.接收:通过对象的属性接收参数,如:user.getUserName();
        c.发送:使用对象的属性传递参数,如:user2!add?user.userName=mike;
    3.使用ModelDriven接收参数(现在用的比较多的方式):
        a.定义:Action实现ModelDriven泛型接口,定义Model类的对象(必须new),通过getModel方法返回该对象;
        b.接收:通过对象的属性接收参数,如:user.getUserName();
        c.发送:直接使用属性名传递参数,如:user2!add?userName=tom


    在Struts2.3.4的文档里面有这样说明:
    To use ModelDriven actions, make sure that the Model Driven Interceptor is applied to your action. This interceptor is part of the default interceptor stack defaultStack so it is applied to all actions by default.

    Action class:

    Java代码 复制代码 收藏代码
    1. public class ModelDrivenAction implements ModelDriven {    
    2.     public String execute() throws Exception {   
    3.         return SUCCESS;   
    4.     }   
    5.   
    6.     public Object getModel() {   
    7.         return new Gangster();   
    8.     }   
    9. }  
    public class ModelDrivenAction implements ModelDriven { 
        public String execute() throws Exception {
            return SUCCESS;
        }
    
        public Object getModel() {
            return new Gangster();
        }
    }
    


    JSP for creating a Gangster:

    Java代码 复制代码 收藏代码
    1. <s:form action="modelDrivenResult" method="POST" namespace="/modelDriven">      
    2.     <s:textfield label="Gangster Name" name="name" />   
    3.     <s:textfield label="Gangster Age"  name="age" />   
    4.     <s:checkbox  label="Gangster Busted Before" name="bustedBefore" />   
    5.     <s:textarea  cols="30" rows="5" label="Gangster Description" name="description" />              
    6.     <s:submit />   
    7. </s:form>  
    <s:form action="modelDrivenResult" method="POST" namespace="/modelDriven">   
        <s:textfield label="Gangster Name" name="name" />
        <s:textfield label="Gangster Age"  name="age" />
        <s:checkbox  label="Gangster Busted Before" name="bustedBefore" />
        <s:textarea  cols="30" rows="5" label="Gangster Description" name="description" />           
        <s:submit />
    </s:form>
    



    在Model Driven Interceptor里面这样说道
    To create a Model Driven action, implement the ModelDriven interface by adding a model property, or at least the accessor.

    public Object getModel() ...

    In the implementation of getModel, acquire an instance of a business object and return it.

    On the page, you can address any JavaBean properties on the business object as if they were coded directly on the Action class. (The framework pushes the Model object onto the ValueStack.)

    Many developers use Spring to acquire the business object. With the addition of a setModel method, the business logic can be injected automatically.

    所以如果实现 ModelDriven 接口,那么必须至少构造一个getModel方法,并return一个实体对象。而且在struts.xml文件中需要配置名为modelDriven的拦截器Interceptor,如果没有指定拦截器栈,那么使用默认的defaultStack,这个拦截器栈里面已经引用了modelDriven的拦截器,所以默认下你的package包extends了struts-default那么就不用配置。
    struts.xml:

    Java代码 复制代码 收藏代码
    1. <action name="someAction" class="com.examples.SomeAction">   
    2.     <interceptor-ref name="modelDriven"/>   
    3.     <interceptor-ref name="basicStack"/>   
    4.     <result name="success">good_result.ftl</result>   
    5. </action>  
    <action name="someAction" class="com.examples.SomeAction">
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="basicStack"/>
        <result name="success">good_result.ftl</result>
    </action>
    



    Struts2默认的拦截器栈:

    Java代码 复制代码 收藏代码
    1.     <!-- A complete stack with all the common interceptors in place.   
    2.          Generally, this stack should be the one you use, though it   
    3.          may do more than you need. Also, the ordering can be   
    4.          switched around (ex: if you wish to have your servlet-related   
    5.          objects applied before prepare() is called, you'd need to move   
    6.          servletConfig interceptor up.   
    7.   
    8.          This stack also excludes from the normal validation and workflow   
    9.          the method names input, back, and cancel. These typically are   
    10.          associated with requests that should not be validated.   
    11.     -->   
    12.     <interceptor-stack name="defaultStack">   
    13.         <interceptor-ref name="exception"/>   
    14.         <interceptor-ref name="alias"/>   
    15.         <interceptor-ref name="servletConfig"/>   
    16.         <interceptor-ref name="i18n"/>   
    17.         <interceptor-ref name="prepare"/>   
    18.         <interceptor-ref name="chain"/>   
    19.         <interceptor-ref name="scopedModelDriven"/>   
    20.         <interceptor-ref name="modelDriven"/>   
    21.         <interceptor-ref name="fileUpload"/>   
    22.         <interceptor-ref name="checkbox"/>   
    23.         <interceptor-ref name="multiselect"/>   
    24.         <interceptor-ref name="staticParams"/>   
    25.         <interceptor-ref name="actionMappingParams"/>   
    26.         <interceptor-ref name="params">   
    27.                  <param name="excludeParams">dojo\..*,   
    28.                  ^struts \..*,^session\..*,^request\..*,^application\..*,   
    29.                  ^servlet(Request|Response)\..*,parameters\...*   
    30.                  </param>   
    31.         </interceptor-ref>   
    32.         <interceptor-ref name="conversionError"/>   
    33.         <interceptor-ref name="validation">   
    34.             <param name="excludeMethods">input,back,cancel,browse</param>   
    35.         </interceptor-ref>   
    36.         <interceptor-ref name="workflow">   
    37.             <param name="excludeMethods">input,back,cancel,browse</param>   
    38.         </interceptor-ref>   
    39.         <interceptor-ref name="debugging"/>   
    40.     </interceptor-stack>   
    41.   
    42. <default-interceptor-ref name="defaultStack"/>   
    43.   
    44. <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />  
                <!-- A complete stack with all the common interceptors in place.
                     Generally, this stack should be the one you use, though it
                     may do more than you need. Also, the ordering can be
                     switched around (ex: if you wish to have your servlet-related
                     objects applied before prepare() is called, you'd need to move
                     servletConfig interceptor up.
    
                     This stack also excludes from the normal validation and workflow
                     the method names input, back, and cancel. These typically are
                     associated with requests that should not be validated.
                -->
                <interceptor-stack name="defaultStack">
                    <interceptor-ref name="exception"/>
                    <interceptor-ref name="alias"/>
                    <interceptor-ref name="servletConfig"/>
                    <interceptor-ref name="i18n"/>
                    <interceptor-ref name="prepare"/>
                    <interceptor-ref name="chain"/>
                    <interceptor-ref name="scopedModelDriven"/>
                    <interceptor-ref name="modelDriven"/>
                    <interceptor-ref name="fileUpload"/>
                    <interceptor-ref name="checkbox"/>
                    <interceptor-ref name="multiselect"/>
                    <interceptor-ref name="staticParams"/>
                    <interceptor-ref name="actionMappingParams"/>
                    <interceptor-ref name="params">
                             <param name="excludeParams">dojo\..*,
                             ^struts \..*,^session\..*,^request\..*,^application\..*,
                             ^servlet(Request|Response)\..*,parameters\...*
                             </param>
                    </interceptor-ref>
                    <interceptor-ref name="conversionError"/>
                    <interceptor-ref name="validation">
                        <param name="excludeMethods">input,back,cancel,browse</param>
                    </interceptor-ref>
                    <interceptor-ref name="workflow">
                        <param name="excludeMethods">input,back,cancel,browse</param>
                    </interceptor-ref>
                    <interceptor-ref name="debugging"/>
                </interceptor-stack>
    ......
            <default-interceptor-ref name="defaultStack"/>
    
            <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />
    
    



    下面这段代码可以充分体现ModelDriven和Preparable接口结合JAVA反射机制的灵活用法,大大方便节省了开发code时间,注意这里用的是paramsPrepareParamsStack拦截器栈,所以params拦截器会在Preparable接口的方法之前执行。

    Java代码 复制代码 收藏代码
    1. public abstract class AbstractBaseAction<T> extends ActionSupport implements ModelDriven<T>,Preparable{   
    2.   
    3.     private static final long serialVersionUID = -1487318639557604204L;   
    4.        
    5.     private T entity;   
    6.        
    7.     private Class<T> entityClass;   
    8.        
    9.     private Long id;   
    10.        
    11.     public T getModel() {   
    12.         return entity;   
    13.     }   
    14.        
    15.     public void setModel(T entity) {   
    16.         this.entity = entity;   
    17.     }   
    18.        
    19.     @SuppressWarnings("unchecked")   
    20.     public AbstractBaseAction() {   
    21.         try {   
    22.             entityClass =(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];   
    23.             if (entity == null) {   
    24.                 try {   
    25.                     entity = entityClass.newInstance();   
    26.                 } catch (Exception e) {   
    27.                     ExceptionHandler.logError(e, AbstractBaseAction.class,"创建实例失败,class=" + entityClass.getName());   
    28.                 }   
    29.             }   
    30.         } catch (Exception e) {   
    31.             ExceptionHandler.logError(e, AbstractBaseAction.class,"无法获取entityClass ");   
    32.         }   
    33.     }   
    34.        
    35.     @Override  
    36.     public void prepare() throws Exception {   
    37.            
    38.     }   
    39.        
    40.     public void prepareSave() throws Exception {   
    41.     }   
    42.        
    43.     public String save() throws Exception{   
    44.         return SUCCESS;   
    45.     }   
    46.        
    47.     public void prepareDelete() throws Exception {   
    48.     }   
    49.        
    50.     public String delete() throws Exception{   
    51.         return SUCCESS;   
    52.     }   
    53.        
    54.     public void prepareLoad() throws Exception {   
    55.     }   
    56.        
    57.     public String load() throws Exception{   
    58.         return SUCCESS;   
    59.     }   
    60.        
    61.     public String list() throws Exception{   
    62.         return SUCCESS;   
    63.     }   
    64.   
    65.     public Long getId() {   
    66.         return id;   
    67.     }   
    68.   
    69.     public void setId(Long id) {   
    70.         this.id = id;   
    71.     }   
    72.   
    73. }  
  • 相关阅读:
    自我介绍
    目前流行的源程序版本管理软件和项目管理软件的优缺点
    四月是你的谎言
    软件分析(Mobile Apps )--百词斩
    程序扩展
    超级无敌小学四则运算题目程序
    4组 团队展示
    2020面向对象设计与构造 第四单元 & 课程 博客总结
    2020面向对象设计与构造 第三单元 博客总结
    2020面向对象设计与构造 第二单元 博客总结
  • 原文地址:https://www.cnblogs.com/123a/p/2697963.html
Copyright © 2011-2022 走看看