请求重定向与请求转发的比较,HttpServletResponse.sendRedirect方法和RequestDispatcher.forward方法都可以让浏览器获得另外一个URL所指向的资源,但两者的内部运行机制有很大的区别。

1.RequestDispatcher.forward()方法只能将请求转发给同一个Web应用中的组件,HttpServletResponse.sendRedirect不仅可以重定向到当前应用程序的其他资源,还可以重定向到同一个站点上的其他应用程序的资源,甚至是使用绝对URL重定向到其他站点的资源。对于sendRedirect如果传递的URL以”/”开头,他是相对于整个Web站点的根目录;对于forward如果传递的URL以”/”开头,它是相对于当前Web应用程序的根目录。

2.response.sendRedirect()对浏览器做出的响应是重新发出对另外一个URL的访问请求,forward在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求并得到了响应结果

3.forward的调用者与被调用者之间共享相同的request对象和response对象,他们属于同一个访问请求和响应过程;sendRedirect的调用者与被调用者使用各自的request和response对象,属于两个独立的访问请求和响应过程

请求重定向以redirect:开头,请求转发以forward:开头;
样例如下:

@RequestMapping(value="/users")
@Controller
public class UserController {

    @RequestMapping(value="/queryuser",method = RequestMethod.GET)
    public String queryuser(Model model) throws Exception {
        return "forward:/users/uc";
    }

    @RequestMapping(value="/uc",method = RequestMethod.GET)
    public String quer(Model model) throws Exception {

        return "redirect:/#/home";
    }

     @RequestMapping(value = "/save", method = RequestMethod.GET)  
        public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) throws Exception {  
            ModelAndView mv = new ModelAndView("forward:/users/uc");//默认为forward模式 
// ModelAndView mv = new ModelAndView("redirect:/#/home");//redirect模式 
            return mv;  
        } 
}