区别

  • 重定向:sendRedirect();浏览器url会改变,request与response均改变,不在原来的请求范围内。
  • 转发:forward();url不会改变,request和response也会跟过去。
  • 转发是服务器行为,重定向是浏览器行为。
  • 转发,浏览器只做一次请求,重定向至少两次

    应用

  • 重定向的速度比转发慢,因为浏览器还要发出一个新的请求,所以在使用两种方法都无所谓的情况下建议使用转发。Spring中使用的就是转发,如

    @RequestMapping("/register")
    public ModelAndView register(){
        logger.info("----请求注册页面----");
        ModelAndView modelAndView=new ModelAndView("/jsp/register");
        return modelAndView;
    }
    
    @RequestMapping(value="/register_check",method=RequestMethod.POST)
    public String register(HttpServletRequest request, HttpServletResponse response
            , Model model) throws UnknownHostException {
    
        //用户名
        String username=request.getParameter("username");
    
        //判空
        if(StringUtil.isNull(username)){
            model.addAttribute("message","请填写用户名");
            return "/jsp/register";
        }
    
  • 转发只能访问当前web的应用程序,如果是要访问到另外一个web站点的资源,就只能使用重定向。Spring要使用重定向的话且需要将属性也送过去的话:

    //在spring-mvc文件添加(放在这个值负责处理controller层的文件即可)
    //不要放在总的applicationContext.xml中,会导致很多controller注册的url失效
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    http://www.springframework.org/schema/mvc 
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    
    <mvc:annotation-driven/>
    
    //在controller中方法上添加入参:org.springframework.web.servlet.mvc.support.RedirectAttributes
    @RequestMapping(value="saveProduct",method=RequestMethod.POST)
    public String saveProduct(ProductForm productForm,RedirectAttributes redirectAttributes){
         //传递参数
           redirectAttributes.addFlashAttribute("message","The product is saved successfully");
    
         //执行重定向
          return "redirect:/……";
    }
    
  • 重定向是重新发起了一次请求,需要写个对应的controller来处理该请求,而转发则可以直接找到视图,不需要再经过controller处理。
  • 代码实例:D:/ideaprojects/thz/thz-manager-web/spring-mvc.xml、WebPageController
  • 重定向有一个重要的应用场景:避免在用户重新加载页面时两次调用相同的动作。例如,当提交产品表单时,执行保存方法,信息被添加到数据库。但是如果在提交后,重新加载页面,保存方法就很可能被再次执行,从而出现错误。为了避免这种情况,表单提交后可以将用户重定向到一个不同的页面,从而使得多次重新加载都没有副作用。