浅谈ActionForward的三种重定向

来源:互联网 发布:域名免备案 编辑:程序博客网 时间:2024/06/05 03:42
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方法时用到的重定向方法:

示例代码如下:

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;               } 


声明:OSCHINA 博客文章版权属于作者,受法律保护。未经作者同意不得转载。

0 0