動態(tài)方法就是一個Action對應(yīng)多個請求,減少Action的數(shù)量
1、指定method屬性
1
2
3
|
< result >/jsp/add.jsp</ result > </ action > |
2、感嘆號(!)方式(不推薦使用)
1
2
3
4
5
|
< action name = "HelloWorld" class = "com.venn.action.HelloWorldAction" > < result >/jsp/test.jsp</ result > < result name = "add" >/jsp/add.jsp</ result > < result name = "update" >/jsp/update.jsp</ result > </ action > |
需要在struts.xml中加入如下常量:
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>(加在package標(biāo)簽外面)
調(diào)用不同方法使用:
訪問execute方法: http://localhost:8080/TestStruts2/HelloWorld.action
訪問update方法: http://localhost:8080/TestStruts2/HelloWorld!update.action
訪問add方法 http://localhost:8080/TestStruts2/HelloWorld!add.action
3、通配符方式
Action配置:
1
2
3
4
5
|
< action name = "HelloWorld_*" method = "{1}" class = "com.venn.action.HelloWorldAction" > < result >/jsp/test.jsp</ result > < result name = "add" >/jsp/add.jsp</ result > < result name = "update" >/jsp/update.jsp</ result > </ action > |
訪問execute方法: http://localhost:8080/TestStruts2/HelloWorld.action 或http://localhost:8080/TestStruts2/HelloWorld_execute.action
訪問add方法 http://localhost:8080/TestStruts2/HelloWorld_add.action
注:為簡化struts.xml配置,可以將action配置為:
1
2
3
4
5
|
< action name = "*_*_*" method = "{2}" class = "com.venn.{3}.{1}Action" > < result >/jsp/test.jsp</ result > < result name = "add" >/jsp/{2}.jsp</ result > < result name = "update" >/jsp/{2}.jsp</ result > </ action > |
第一個*對應(yīng)action,第二個*對應(yīng)method
注意result標(biāo)簽的name屬性不可以使用通配符
java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class HelloWorldAction extends ActionSupport { @Override public String execute() throws Exception { System.out.println( "execute method" ); return "success" ; } public String add(){ System.err.println( "add method" ); return "add" ; } public String update(){ System.out.println( "update method" ); return "update" ; } } |
總結(jié)
以上就是本文關(guān)于詳解Struts2動態(tài)方法調(diào)用的全部內(nèi)容,希望對大家有所幫助。有什么問題可以隨時留言,小編會盡快回復(fù)大家。
原文鏈接:http://www.cnblogs.com/Springmoon-venn/p/5578965.html