Struts2的动态方法调用DMI


在写Struts的Action类的时候,经常遇到不希望每次调用的都是execute方法,希望能动态的调用一些其他的方法,这里Struts提供了两种方式,第一种是在strust.xml中进行method这个属性的配置,但是这样每次只能配置一个,而且是死值,不方便动态的更换和调用,所以这里介绍DMI,动态的方法的调用。

下面我们先写出来Action

  1. package com.bird.test;  
  2.   
  3. import com.opensymphony.xwork2.ActionSupport;  
  4.   
  5. public class IndexAction extends ActionSupport{  
  6.   
  7.     private static final long serialVersionUID = 1L;  
  8.       
  9.     @Override  
  10.     public String execute() throws Exception {  
  11.         return SUCCESS;  
  12.     }  
  13.       
  14.     public String test(){  
  15.         return ERROR;  
  16.     }  
  17.   
  18.       
  19. }  

这个action里面既有execute方法,也有test方法,我们的目的就是去动态的调用它的test方法

下面看一下它的对应的struts.,xm文件的配置

  1. <constant name="struts.devMode" value="true"/>  
  2.  <package name="front" namespace="/front" extends="struts-default">  
  3.     <action name="index" class="com.bird.test.IndexAction">  
  4.         <result name="success">/Hello.jsp</result>  
  5.         <result name="error">/test.jsp</result>  
  6.     </action>  
  7.  </package>  

没有什么特殊的配置,最重要的就是访问的时候的url地址的写法

这里写为

http://localhost:8080/Struts2/front/index!test

分别的意思是,调用命名空间/front下面的indexaction里面的test方法,特别注意的就是感叹号!!!index!test

这就是DMI动态方法调用,一个简单的非常实用 的功能。

相关内容