ActionForward的使用
1、ActionForward包含转向信息
2、全局forward和局部forward
* 全局forward,若很多个Action处理完后都要转向到某页面,不妨把该页面设为全局forward:
<global-forwards>
<forward name="login" path="/login.jsp" redirect="true"/>
</global-forwards>
* 局部forward:
<action path="/login"
type="cn.huan.struts.LoginAction"
name="loginForm"
scope="request"
>
<forward name="success" path="/login_success.jsp"/>
<forward name="error" path="/login_error.jsp"/>
</action>
* mapping.findForward方法会先自动找配置中的局部forward,若没有就找全局forward
3、转发和重定向
转向:同一个request
重定向:需设置redirect="true",另建一个新request,故改变了url
4、转发和重定向都可以自己定义而不用struts提供的ActionForward
在Action中自定义转向:
RequestDispatcher dispatcher = request.getRequestDispatcher("/mustlogin.jsp");
dispatcher.forward(request, response);
return null;
在Action中自定义重定向:
response.sendRedirect(request.getContextPath() + "/login.jsp");
return null;
5、struts-config.xml文件和web.xml文件在运行时都不能动态修改,也就是不能再在Action中改已配置好的属性值
6、动态ActionForward
不需要修改Action代码和增加<forward>配置
例如:如果需要根据页面输入的值动态的跳转到不同页面:
<form action="dynaactionforward.do" method="post">
页面:<input type="text" name="page"><br>
<input type="submit" value="提交">
</form>
则用动态ActionForward可很好地实现,Action和配置信息分别为(其中注释部分为没有使用动态 ActionForm时的代码):
Action代码:
package cn.huan.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* 动态ActionForwad测试
* @author 刘银环
*
*/
public class DynaActionForwardTestAction extends Action {
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
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;
//动态ActionForward
ActionForward af = new ActionForward();
af.setPath("/page" + page + ".jsp");
return af;
}
}
配置信息:
<action path="/dynaactionforward"
type="cn.huan.struts.DynaActionForwardTestAction">
<!--
<forward name="page1" path="/page1.jsp"/>
<forward name="page2" path="/page2.jsp"/>
-->
</action>