SpringMVC redirect重定向传参

关于SpringMVC 重定向传参的问题一直无解,每次碰到有关需求就去网上找资料,通常情况就是问题解决了知识点就忘记了。然而网上资料太凌乱,每次都要一个个重新测试才能找到正确答案,所以这次痛下决心,记录一下这次问题,免得下次碰到又不会,嘻嘻。

SpringMVC redirect传参总共有3种情况,现在一一说明。

第一种:手动拼接url,当涉及到中文时会乱码,不推荐,其他情况自己斟酌使用。

    @RequestMapping(value="/get/{id}")
    public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp,
            ModelMap model) {
        return "redirect:/billManage?bill_get_id="+id;
    }

第二种:自动拼接url,可以使用ModelMap或者RedirectAttributes,使用这个方法地址栏的url会自动添加?bill_get_id=xxx

    @RequestMapping(value="/get/{id}")
    public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp,
            ModelMap model,RedirectAttributes attr) {
        attr.addAttribute("bill_get_id", id);
        return "redirect:/billManage";
    }

第三种:不拼接url,也即url后面不添加参数,使用RedirectAttributes来实现,估计使用最多的就是这种了。当页面重新刷新时,参数会丢失。

    @RequestMapping(value="/get/{id}")
    public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp,
            ModelMap model,RedirectAttributes attr) {
        attr.addFlashAttribute("bill_get_id", id);
        return "redirect:/billManage";
    }


重定向的controller

    @RequestMapping(value="/billManage")
    public String index(@ModelAttribute("bill_get_id") String billId, HttpServletRequest req, HttpServletResponse resp,
            ModelMap model) {
        model.addAttribute("bill_get_id", billId);
        return "bill/billManage";
    }

页面可以直接使用el表达式来获取bill_get_id的值。

var billID = '${bill_get_id}';

特别注意:通过第三种方式跳转后,重新刷新页面,参数会丢失。


猜你喜欢

转载自blog.csdn.net/wangli61289/article/details/78357263