Struts2中有时可能会需要使用一个Action来处理多个请求,来提高编码的效率和减少代码量。例如,在登录界面上的表单中可能会有登录和注册两个事件请求,有几种方式可以借鉴:
1.采用DMI动态调用方法。
该方法的主要思想是在一个 Action 类中实现多个方法,然后每个 action 请求中表明要调用该类中的哪个方法。使用 actionname!method 方式调用。
(1)LoginAction 类代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 package com.main.action; 2 3 import com.opensymphony.xwork2.ActionSupport; 4 5 public class LoginAction extends ActionSupport { 6 private String username; 7 private String psd; 8 9 public String login(){10 if ("lihui".equals(username) && "xhh".equals(psd)) {11 return SUCCESS;12 } else {13 return ERROR;14 }15 }16 17 public String regist(){18 return "regist";19 }20 21 public void setUsername(String username){22 this.username = username;23 }24 25 public String getUsername(){26 return this.username;27 }28 29 public void setPsd(String psd){30 this.psd = psd;31 }32 33 public String getPsd(){34 return this.psd;35 }36 }
(2)struts.xml 配置如下:
1 2 5 67 8 149 13/success.jsp 10/error.jsp 11/regist.jsp 12
(3)在jsp中的action请求代码如下:
1 2 915
2.直接指定 Action 元素的 method 属性
使用这个方法就不必用 ! 将action和method连接后调用了,struts.xml 配置如下:
12 3 114 7/success.jsp 5/error.jsp 68 10/regist.jsp 9
3.使用通配符处理
<action>的属性name class method 都支持通配符。struts.xml 配置如下:
12 3 94 8/success.jsp 5/error.jsp 6/regist.jsp 7
关键就在于第三行代码, login_* 使用了通配符,所以接收所有类似的action请求,至于调用该类中的哪个方法,就看method="{1}",表示使用name属性第一个*的值。例如,在本例中,form的action属性值设置为 login_regist,则调用com.main.action.LoginAction类中的regist()方法。
此外,Struts支持默认 Action 请求。当系统找不到指定的Action时,则交给默认的Action去处理。在struts.xml中的配置为:
<package ...>
<default-action-ref name="login"></default-action-ref>
</package>
转自: