设为首页 加入收藏

TOP

Struts2中action接收参数的三种方法及ModelDriven跟Preparable接口结合JAVA反射机制的灵活用法
2019-05-11 14:10:22 】 浏览:130
Tags:Struts2 action 接收 参数 方法 ModelDriven Preparable 接口 结合 JAVA 反射 机制 灵活 用法
Struts2中action接收参数的三种方法及ModelDriven和Preparable接口结合JAVA反射机制的灵活用法
Struts2中Action接收参数的方法主要有以下三种:

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

  1. publicclassModelDrivenActionimplementsModelDriven{
  2. publicStringexecute()throwsException{
  3. returnSUCCESS;
  4. }
  5. publicObjectgetModel(){
  6. returnnewGangster();
  7. }
  8. }

JSP for creating a Gangster:
  1. <s:formaction="modelDrivenResult"method="POST"namespace="/modelDriven">
  2. <s:textfieldlabel="GangsterName"name="name"/>
  3. <s:textfieldlabel="GangsterAge"name="age"/>
  4. <s:checkboxlabel="GangsterBustedBefore"name="bustedBefore"/>
  5. <s:textareacols="30"rows="5"label="GangsterDescription"name="description"/>
  6. <s:submit/>
  7. </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:

  1. <actionname="someAction"class="com.examples.SomeAction">
  2. <interceptor-refname="modelDriven"/>
  3. <interceptor-refname="basicStack"/>
  4. <resultname="success">good_result.ftl</result>
  5. </action>

Struts2默认的拦截器栈:

  1. <!--Acompletestackwithallthecommoninterceptorsinplace.
  2. Generally,thisstackshouldbetheoneyouuse,thoughit
  3. maydomorethanyouneed.Also,theorderingcanbe
  4. switchedaround(ex:ifyouwishtohaveyourservlet-related
  5. objectsappliedbeforeprepare()iscalled,you'dneedtomove
  6. servletConfiginterceptorup.
  7. Thisstackalsoexcludesfromthenormalvalidationandworkflow
  8. themethodnamesinput,back,andcancel.Thesetypicallyare
  9. associatedwithrequeststhatshouldnotbeva lidated.
  10. -->
  11. <interceptor-stackname="defaultStack">
  12. <interceptor-refname="exception"/>
  13. <interceptor-refname="alias"/>
  14. <interceptor-refname="servletConfig"/>
  15. <interceptor-refname="i18n"/>
  16. <interceptor-refname="prepare"/>
  17. <interceptor-refname="chain"/>
  18. <interceptor-refname="scopedModelDriven"/>
  19. <interceptor-refname="modelDriven"/>
  20. <interceptor-refname="fileUpload"/>
  21. <interceptor-refname="checkbox"/>
  22. <interceptor-refname="multiselect"/>
  23. <interceptor-refname="staticParams"/>
  24. <interceptor-refname="actionMappingParams"/>
  25. <interceptor-refname="params">
  26. <paramname="excludeParams">dojo\..*,
  27. ^struts\..*,^session\..*,^request\..*,^application\..*,
  28. ^servlet(Request|Response)\..*,parameters\...*
  29. </param>
  30. </interceptor-ref>
  31. <interceptor-refname="conversionError"/>
  32. <interceptor-refname="validation">
  33. <paramname="excludeMethods">input,back,cancel,browse</param>
  34. </interceptor-ref>
  35. <interceptor-refname="workflow">
  36. <paramname="excludeMethods">input,back,cancel,browse</param>
  37. </interceptor-ref>
  38. <interceptor-refname="debugging"/>
  39. </interceptor-stack>
  40. ......
  41. <default-interceptor-refname="defaultStack"/>
  42. <default-class-refclass="com.opensymphony.xwork2.ActionSupport"/>

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

  1. publicclassPlayerActionextendsAbstractBaseAction<Player>{
  2. privatestaticfinallongserialVersionUID=-3068068486865209475L;
  3. @Override
  4. publicStringexecute()throwsException{
  5. returnsuper.list();
  6. }
  7. }


  1. publicabstractclassAbstractBaseAction<T>extendsActionSupportimplementsModelDriven<T>,Preparable{
  2. privatestaticfinallongserialVersionUID=-1487318639557604204L;
  3. privateTentity;
  4. privateClass<T>entityClass;
  5. privateLongid;
  6. publicTgetModel(){
  7. returnentity;
  8. }
  9. @SuppressWarnings("unchecked")
  10. publicAbstractBaseAction(){
  11. try{
  12. entityClass=(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
  13. }catch(Exceptione){
  14. ExceptionHandler.logError(e,AbstractBaseAction.class,"无法获取entityClass");
  15. }
  16. }
  17. /**
  18. *这里相当于new了一个entity对象,getModel()才能返回这个对象,
  19. *因为默认的interceptor-stack是defaultStack中prepare在modelDriven拦截器之前执行
  20. */
  21. @Override
  22. publicvoidprepare()throwsException{
  23. if(entity==null){
  24. try{
  25. entity=entityClass.newInstance();
  26. }catch(Exceptione){
  27. ExceptionHandler.logError(e,AbstractBaseAction.class,"创建实例失败,class="+entityClass.getName());
  28. }
  29. }
  30. }
  31. publicvoidprepareSave()throwsException{
  32. if(getId()!=null){
  33. entity=getEntityById(getId());
  34. }
  35. }
  36. publicStringsave()throwsException{
  37. returnSUCCESS;
  38. }
  39. publicvoidprepareDelete()throwsException{
  40. if(getId()!=null){
  41. entity=getEntityById(getId());
  42. }
  43. }
  44. publicStringdelete()throwsException{
  45. returnSUCCESS;
  46. }
  47. publicvoidprepareLoad()throwsException{
  48. if(getId()!=null){
  49. entity=getEntityById(getId());
  50. }
  51. }
  52. publicStringload()throwsException{
  53. returnSUCCESS;
  54. }
  55. publicStringlist()throwsException{
  56. returnSUCCESS;
  57. }
  58. protectedTgetEntityById(Longid){
  59. if(id!=null){
  60. try{
  61. return(T)HibernateUtil.getObjectById(entityClass,id);
  62. }catch(Exceptione){
  63. Struts2Utils.getRequest().setAttribute("error","数据查询出错");
  64. addActionMessage("数据查询出错");
  65. ExceptionHandler.logError(e,AbstractBaseAction.class,"获取实例时出现异常,class="+entityClass.getName()+",id="+getId());
  66. }
  67. }
  68. returnnull;
  69. }
  70. publicLonggetId(){
  71. returnid;
  72. }
  73. publicvoidsetId(Longid){
  74. this.id=id;
  75. }
  76. }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Kafka客户端不进行加密处理的代码.. 下一篇Hive相关链接

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目