SpringMVC中的重定向和转发的实现

1.请求转发和重定向的区别

请求重定向和请求转发都是web开发中资源跳转的方式。

请求转发是服务器内部的跳转

  地址栏比发生变化

  只有一个请求相应

  可以通过request域对跳转目标的请求

请求重定向是浏览器自动发起对跳转目标的请求

  地址栏会发生变化

  两次请求相应

    无法通过request域传递对象

2.SpringMVC中实现转发和重定向

(1)在SpringMVC中仍然可以使用传统方式实现转发和重定向

  request.getRequestDispatcher(" ").forward(request,response);

  response.sendRedirect(" ");

(2)在SpringMVC中也提供了快捷方式实现转发和重定向

只要在返回视图时,使用如下方式指定即可:

    /**
     * 实现转发
     */
    @RequestMapping("/hello11.action")
    public String hello11(HttpServletRequest request){
        request.setAttribute("name", "cjj");
        return "forward:hello.action";
    }
    
    /**
     * 实现重定向
     */
    @RequestMapping("/hello12.action")
    public String hello12(HttpServletRequest request){
        request.setAttribute("name", "cjj");
        return "redirect:/hello.action";
    }

(3)可以利用转发,实现允许用户访问WEB-INF下保存的指定资源

    /**
     * 通过转发 实现 访问到在WEB-INF目录下的资源
     * @throws Exception 
     */
    @RequestMapping("/toFile.action")
    public String toFile(String vname){
        if("form".equals(vname)){
            return vname;
        }else{
            return "err";
        }
    }

猜你喜欢

转载自www.cnblogs.com/chuijingjing/p/9845713.html