假如以下页面, form中指定action为login, 当点击"登陆"按钮时,会调用login这个action的execute方法, 如今但愿当点击"注册"按钮时, 能调用action的另一个方法, 也就是但愿login这个action中有多个处理逻辑, 当用户作某一个操做时, 可以调用相应的处理逻辑, 问题是form元素中只能指定一个action, 默认操做是调用Action的execute方法, 那么其它的操做若是调用Action中相应的方法呢?javascript
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@taglib prefix="s" uri="/struts-tags" %> <html> <head> <script type="text/javascript" src="js/login.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login</title> </head> <body> <s:form action="login" method="post"> <s:textfield name="username" key="user"/> <s:textfield name="password" key="pass"/> <tr> <td><s:submit key="login"/></td> <td><s:submit key="regist" onclick="regist();" /></td> </tr> </s:form> </body> </html>
Struts2的动态方法调用(DMI)能够解决这样的问题, DMI使得表单元素的action属性并非直接等于某个Action的名字, 而是以以下形式指定表单元素的action属性:
action="ActionName!MethodName"
使用DMI的具体步骤以下:
1 设置Struts容许DMI, 即设置常量struts.enable.DynamicMethodInvocation值为true, 方式为在struts.xml中添加加配置<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
2 配置action对应的方法, 方法是在struts.xml文件中action标签下的<allowed-methods>标签下指定方法, 例如这里要指定login这个action的regist方法, 在struts.xml中配置以下:html
<package name="action" extends="struts-default" namespace="/"> <action name="login" class="action.LoginAction"> <result name="input">/login.jsp</result> <result name="error">/view/error.jsp</result> <result name="success">/view/welcome.jsp</result> <allowed-methods>regist</allowed-methods> </action> </package>
3 完善login这个Action, 代码以下:java
package action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport{ private String username; private String password; private String tip; //省略属性的set和get方法 public String regist() throws Exception{ ActionContext.getContext().getSession().put("user", getUsername()); setTip("恭喜您, " + getUsername() + ", 您已成功注册!"); return SUCCESS; } public String execute() throws Exception{ ActionContext ctx = ActionContext.getContext(); Integer counter = (Integer) ctx.getApplication().get("counter"); if(counter == null){ counter = 1; }else{ counter += 1; } ctx.getApplication().put("counter", counter); if(getUsername().equals("toby") && getPassword().equals("toby")){ ActionContext.getContext().getSession().put("user", getUsername()); ctx.put("tip", "服务器提示:您已成功登陆"); return SUCCESS; } else{ ctx.put("tip", "服务器提示:登陆失败"); return ERROR; } } }
4 增长js脚本, 当用户点击注册时, 将表单的action设置为login!regist, 方法是在页面中引入以下脚本:服务器
function regist() { targetForm = document.forms[0]; targetForm.action = "login!regist"; }
这样就完成了DMI配置, 当在登陆页面点击"登陆"时,执行login这个action的execute方法, 当点击
"注册时", 执行login这个Action的regist方法.jsp