Struts(7)Struts的DispatchAction(分派Action)和全局跳转

来源:互联网 发布:java数据库代码生成器 编辑:程序博客网 时间:2024/05/19 15:44

1 为什么需要DispatchAction?

如果每个请求对应一个Action,就会造成Action过多,程序显得比较臃肿,因此程序需要减肥(可以把一类请求写到一个Action中处理),这样程序比较简洁,且利于维护和扩展。

2 DispatchAction开发

这里写图片描述
创建LoginAndLogoutAction 继承自DispatchAction
这里写图片描述
struts-config.xml添加parameter属性

<!-- parameter 用于区分用户不同的请求 --><action  attribute="userForm"  input="/WEB-INF/ok.jsp"  name="userForm"  parameter="flag"  path="/loginAndLogout"  scope="request"  type="com.test.struts.action.LoginAndLogoutAction"  validate="false"  cancellable="true">  <!-- 局部跳转 -->  <forward name="goLogin" path="/WEB-INF/login.jsp" />  <forward name="loginok" path="/WEB-INF/ok.jsp" /></action>

②对应的LoginAndLogoutAction 文件

public class LoginAndLogoutAction extends DispatchAction {    // 使用分派action,往往需要自己重新命名函数    // 该函数用于响应登录请求    public ActionForward userLogin(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        UserForm userForm = (UserForm) form;// TODO Auto-generated method stub        if("123".equals(userForm.getPassword())) {            return mapping.findForward("loginok");        } else {            return mapping.findForward("goLogin");        }    }    // 该函数用于响应注销请求    public ActionForward userLogout(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        UserForm userForm = (UserForm) form;// TODO Auto-generated method stub        //清空session        request.getSession().invalidate();        return mapping.findForward("goerr"); // 全局跳转    }    // 该函数用于响应注销请求    public ActionForward userLogout2(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        UserForm userForm = (UserForm) form;// TODO Auto-generated method stub        //清空session        System.out.println("logout2");        request.getSession().invalidate();        return mapping.findForward("goLogin");    }}

③跳转的URL格式
/dispatchtest/loginAndLogout.do?flag=userLogin

<form action="/dispatchtest/loginAndLogout.do?flag=userLogin" method="post">    u:<input type="text" name="name"><br>    p:<input type="password" name="password"><br>    <input type="submit" value="login"></form>

3 全局跳转和局部跳转

这里写图片描述
全局跳转:指的是所有的action都可以跳转到该页面;

<global-forwards >  <forward name="goerr" path="/WEB-INF/err.jsp" /></global-forwards>

局部跳转:指的是只有本action可以跳转到该页面。

<action  attribute="userForm"  input="/WEB-INF/ok.jsp"  name="userForm"  parameter="flag"  path="/loginAndLogout"  scope="request"  type="com.test.struts.action.LoginAndLogoutAction"  validate="false"  cancellable="true">  <!-- 局部跳转 -->  <forward name="goLogin" path="/WEB-INF/login.jsp" />  <forward name="loginok" path="/WEB-INF/ok.jsp" /></action>
0 0
原创粉丝点击