<global-forwards>
<forward name="success" path="/login_success.jsp"/>
</global-forwards>
上面就是对全局ActionForward的一种配置,而我们之前写的那些就是局部ActionForward。那么如果局部ActionForward和全局ActionForward同时出现,到底是按照哪个配置进行页面跳转呢?规则很简单,采用的是就近原则,就是说如果有局部ActionForward,就按照局部ActionForward就行跳转,如果没有就按照全局的跳转。ActionForward af = mapping.findForward("login");
af.setRedirect(false);
记住要重启服务器,因为struts-config.xml文件不允许动态修改。public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
//重定向
response.sendRedirect(request.getContextPath() + "/login.jsp");
return null;
}
注意:return null是必须的。<action-mappings>
<action path="/dynaactionforward" type="com.bjsxt.struts.DynaActionForwardTestAction">
<forward name="page1" path="/page1.jsp"/>
<forward name="page2" path="/page2.jsp"/>
</action>
</action-mappings>
jsp页面:
<form action="dynaactionforward.do" method="post">
页面:<input type="text" name="page"><br>
<input type="submit" value="提交">
</form>
action:
public class DynaActionForwardTestAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String page = request.getParameter("page");
ActionForward af = null;
if ("1".equals(page)) {
af = mapping.findForward("page1");
}else if ("2".equals(page)) {
af = mapping.findForward("page2");
}
return af;
}
}
但是如果我想在此基础上实现当我输入3,跳转到3的页面,输入4,5……以此类推下去,怎么办呢,如果还是采用这种方式,很麻烦。此时我们可以考虑采用动态ActionForward,说白了就是我们自己构造一个ActionForward,通过new的方式,看一下改后的action:
public class DynaActionForwardTestAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception{
String page = request.getParameter("page");
ActionForward af = new ActionForward();
af.setPath("/page" + page + ".jsp?name=Tom");
return af;
}
}
之后再把xml中的<forward name="page1" path="/page1.jsp"/>,<forward name="page2" path="/page2.jsp"/>删除即可。大家还会发现动态ActionForward还有个好处,就是可以跟参数,此例中传递了name=tom的参数。
四、ActionForward对象定义:
假如路径为String url="index.jsp"
1.ActionForward af = new ActionForward();
af.setPath("url");
2.ActionForward af = new ActionForward("url");
3.ActionForward af= actionMapping.findForward("param");