复习第7点-7.SpringMVC 的响应方式

1.使用ServletAPI实现转发
    /*
    使用HttpServletRequest对象实现请求转发
    */
    @RequestMapping("/httpServletRequest")
    public void method1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("msg", "hello--httpServletRequestForward");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
2.使用 Forward 关键字实现请求转发跳转
    @RequestMapping("/forward")
    public String method2(HttpServletRequest request) {
        request.setAttribute("msg", "hello--forward");
        return "forward:/index.jsp";
    }
3.使用视图解析器实现请求转发
    // 访问路径之后,没有出现结果
    // redirect:不能共享request范围的数据
    @RequestMapping("/redirect1")
    public String redirectLogin1(HttpServletRequest request) {
        request.setAttribute("msg", "hello--redirectLogin1");
        return "redirect:/index.jsp";
    }

    // 访问成功
    @RequestMapping("/redirect2")
    public String redirectLogin2(HttpSession session) {
        session.setAttribute("msg", "hello--redirectLogin2");
        return "redirect:/index.jsp";
    }
redirect和forward的区别
  1. 地址栏的区别
    forward:地址栏不发生变化
    redirect:地址栏显示的是新的url
  2. 数据共享的角度
    forward:转发页面和转发到的页面可以共享request里面的数据
    redirect:转发页面和转发到的页面可以共享session里面的数据
posted @ 2023-01-14 16:54  jsqup  阅读(7)  评论(0编辑  收藏  举报