Struts2方法调用的三种方式

来源:互联网 发布:hadoop yarn 源码下载 编辑:程序博客网 时间:2024/06/11 04:21

转载自 http://blog.csdn.net/itmyhome1990/article/details/9265909

在Struts2中方法调用概括起来主要有三种形式

 

第一种方式:指定method属性

[html] view plaincopy
  1. <action name="student" class="com.itmyhome.Student" method="add">   
  2.             <result name="add">/success.jsp</result>   
  3.         </action>   

这样Struts2就会调用Student 中的add方法。

 

第二种方式:动态方法调用(DMI)

用这种方法需要设置一个常量

[html] view plaincopy
  1. <constant name="struts.enable.DynamicMethodInvocation" value="true" />   


动态方法调用是指表单元素的action并不是直接等于某个Action的名字,而是以如下形式来指定Form的action属性

[html] view plaincopy
  1. <!-- action属性为action!methodName的形式 -->   
  2.         action = "action!methodName.action"   


在struts.xml中定义如下Action

[html] view plaincopy
  1. <action name="student" class="com.itmyhome.StudentAction">   
  2.             <result name="add">/add.jsp</result>   
  3.             <result name="delete">/delete.jsp</result>   
  4.         </action>   


StudentAction代码为

[java] view plaincopy
  1. public class StudentAction extends ActionSupport {  
  2.     public String add(){  
  3.         return "add";  
  4.     }  
  5.     public String delete(){  
  6.         return "delete";  
  7.     }  
  8. }  

 

则在JSP中用如下方式调用方法

[html] view plaincopy
  1. <a href="student!add.action">  新增学生</a>  
  2.    <a href="student!delete.action"> 删除学生</a>  


第三种方式:通配符(推荐使用)

[html] view plaincopy
  1. <action name="student*" class="com.itmyhome.StudentAction" method="{1}">  
  2.             <result name="{1}">/student{1}.jsp</result>  
  3.         </action>  

[html] view plaincopy
  1. <a href="studentadd">  新增学生</a>  
  2.    <a href="studentdelete"> 删除学生</a>  

studentadd就会调用StudentAction中的add方法 然后跳转到studentadd.jsp
studentdelete就会调用StudentAction中的delete方法 然后跳转到studentdelete.jsp

 

Struts2支持动态方法调用,它指的是一个Action中有多个方法,系统根据表单元素给定的action来访问不同的方法,而不用写多个Action。


0 0