ActionForward是 Struts的核心类之一,其基类仅有4个属性name / path / redirect / classname。在基于Struts的Web应用程序开发过程当中,Action操做完毕后程序会经过Struts的配置文件struts- config.xml连接到指定的ActionForward,传到Struts的核心类ActionServlet,ActionServlet使用 ActionForward提供的路径,将控制传递给下一个JSP或类。ActionForward控制接下来程序的走向。ActionForward表明一个应用的URI,它包括路径和参数,例如:path=”/login.jsp” 或path=“/modify.do?method=edit&id=10” ActionForward的参数除了在struts-config.xml和页面中设置外,还能够经过在Action类中添加参数,或从新在Action中建立一个ActionForward。
actionForward的做用:封装转发路径,通俗点说就是说完成页面的跳转和转向。那它既然是转向,究竟是转发仍是重定向呢?默认的状况下,actionForward采用的是转发的方式进行页面跳转的。
顺便说一下
转发和重定向的区别。最大的区别就是转发的时候,页面的url地址不变,而重定向的时候页面的url地址会发生变化。简单说明一下缘由,由于转发的时候是采用的同一个request(请求),既然页面跳转先后是同一个request,页面url固然不会变了;而重定向采用的是2个request,由于是二次转发页面跳转先后的url固然会不一样了。
既然actionForward跳转的方式默认的是转发,那若是我非要用重定向的方式,该如何设置呢?恩,这很简单,你们都在struts-config.xml作过actionForward的配置吧,好比这句
<forward name=”login” path=”/login.jsp” redirect=”true”/>
如下是三种经常使用的在action中覆盖execute方法时用到的重定向方法:
示例代码以下: html
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
/****重定向的三种方法*******/
//方法1
response.sendRedirect(request.getContextPath() + "/login.jsp");
return null;
//方法2
ActionForward forward = mapping.findForward("login");
forward.setRedirect(true);
return forward ;
//方法3
PrintWriter out = null;
try
{
// 设置回发内容编码,防止弹出的信息出现乱码
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
String alertString = "你好!这是返回信息!";
String redirectURL = request.getContextPath() + "/login.jsp" ;
out.print("<script>alert('" + alertString + "')</script>");
out.print("<script>window.location.href='" + redirectURL + "'</script>");
out.flush();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}