一、普通的Action被调用,不管怎么被调用都是执行同一个函数execute(),而选择分派Action可以在一个action里写多个执行函数,然后通过(提交给xx.do的时候)传不同的参数(xx.do?xx=xx)来分别调用不同的执行函数。
1.新建一个web项目StrutsLogin
2.WEB-INF下新建login.jsp
<!-- 交给logins.do处理的时候还附带了一个参数信息flag=login --> <form action="logins.do?flag=login" method="post"> u:<input type="text" name="name"><br/> p:<input type="password" name="password"><br/> <input type="submit" value="提交"> <!-- 交给logins.do处理的时候还附带了一个参数信息flag=exit --> <button><a href="login.do?flag=exit">退出</a></button> </form>
3.com.actions包下新建DispatchAction.java,两个用来处理的函数名称分别为login和exit
package com.actions; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class DispatchAction extends org.apache.struts.actions.DispatchAction{ public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub return mapping.findForward("login"); } public ActionForward exit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub return mapping.findForward("exit"); } }
3.配置struts-config.xml
<struts-config> <form-beans> <form-bean name="userForm" type="com.forms.UserForm"></form-bean> </form-beans> <action-mappings> <action path="/logins" input="/WEB-INF/login.jsp" attribute="userForm" name="userForm" parameter="flag" scope="request" type="com.actions.DispatchAction"> <forward name="login" path="/WEB-INF/ok.jsp"></forward> <forward name="exit" path="/WEB-INF/exit.jsp"></forward> </action> </action-mappings> </struts-config>