spring MVC 转发与重定向(传参)


return "forward:index.jsp"; //转发 
return "forward:user.do?method=reg5"; //转发
return new ModelAndView("/toList");//转发
return "redirect:user.do?method=reg5"; //重定向
return "redirect:http://www.baidu.com"; //重定向
return new ModelAndView("redirect:/toList"); //重定向

重定向传参

 方式一:自己手动拼接url

                    new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2);
                    这样有个弊端,就是传中文可能会有乱码问题。

  方式二:用RedirectAttributes,这个是发现的一个比较好用的一个类
                    这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
                    使用方法:

                     attr.addAttribute("param", value);
                    return "redirect:/namespace/toController";

  方式三:带参数不拼接url页面也能拿到值(重点是这个)
                 一般我估计重定向到都想用这种方式:

    @RequestMapping("/save")
    public String save(@ModelAttribute("form") Bean form,
            RedirectAttributes attr) throws Exception {
        String code = service.save(form);
        attr.addFlashAttribute("name", form.getName());
        attr.addFlashAttribute("success", "添加成功!");
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String save(@ModelAttribute("form") Bean form,
            RedirectAttributes attr) throws Exception {
        return "redirect:/main/list";
    }

页面取值直接用el表达式就能获得到,这里的原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM