20_2 Spring MVC web系列 - 重定向和转发
20_2 Spring MVC web系列 - 重定向和转发
一、重定向
1.1 response.sendRedirect重定向跳转
    @GetMapping("/redirect/function1")
    public void function1(HttpServletResponse response) throws IOException {
        response.sendRedirect("https://www.baidu.com");
        //response.sendRedirect("/redirect1.html");
    }
可以直接跳转到外部链接,或者内部链接
1.2 ViewResolver直接跳转
    @GetMapping("/redirect/function2")
    public String function2() throws IOException {
        return "redirect:/redirect1.html";
    }
跳转到内部链接,交由ViewResolver解析处理。
1.2.1 ViewResolver跳转带参数
    @GetMapping("/redirect/function2WithParam")
    public String function2WithParam(RedirectAttributes attr) throws IOException {
        attr.addAttribute("test", "51gjie");//跳转地址带上test参数
        attr.addFlashAttribute("u2", "51gjie");//u2参数不会跟随在URL后面
        return "redirect:/redirect1.html";
    }
- 使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为http:/index.action?test=51gjie
- 使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,这里的redirect必须是方法映射路径,jsp无效。你会发现redirect后的jsp页面中b只会出现一次,刷新后b再也不会出现了,这验证了上面说的,b被访问后就会从session中移除。对于重复提交可以使用此来完成.
- spring mvc设置下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect=true,这样可以提高效率,避免不必要的检索。
1.3 ModelAndView重定向
    @GetMapping("/redirect/function3")
    public ModelAndView function3() throws IOException {
        ModelAndView model = new ModelAndView("redirect:/redirect1.html");
        return model;
    }
1.3.1 ModelAndView重定向带参数
    @GetMapping("/redirect/function3WithParam")
    public ModelAndView function3WithParam() throws IOException {
        ModelAndView model = new ModelAndView("redirect:/redirect1.html");
        model.addObject("userName", "张三");  //把userName参数带入到controller的RedirectAttributes
        return model;
    }
二、请求转发
2.1 ViewResolver请求转发
    @GetMapping("/forward/function1")
    public String function1() {
        return "forward:/forward1.html";
    }
2.1.1 ViewResolver请求转发带参数
    @GetMapping("/forward/function1WithParam")
    public String function1WithParam(HttpServletRequest request) {
        request.setAttribute("username", "张三");////把username参数传递到request中
        return "forward:/forward1.html";
    }
2.2 ModelAndView请求转发
    @GetMapping("/forward/function2")
    public ModelAndView function2() {
        ModelAndView model = new ModelAndView("forward:/forward1.html");//默认forward,可以不用写
        return model;
    }
2.2.1 ModelAndView请求转发带参数
    @GetMapping("/forward/function2WithParam")
    public ModelAndView function2WithParam() {
        ModelAndView model = new ModelAndView("forward:/forward1.html");//默认forward,可以不用写
        model.addObject("userName", "张三");  //把userName参数带入到controller的RedirectAttributes
        return model;
    }
    知行合一
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号