4

解决SpringMVC重定向参数无法携带问题 - look-word

 1 year ago
source link: https://www.cnblogs.com/look-word/p/16980746.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解决SpringMVC重定向参数无法携带问题

重定向时请求参数会丢失,我们往往需要重新携带请求参数,我们可以进⾏⼿动参数拼接如下:

return "redirect:handle01?name=" + name;
  • 但是上述拼接参数的⽅法属于get请求,携带参数⻓度有限制,参数安全性也不⾼,此时,我们可以使用SpringMVC提供的flash属性机制
  • 向上下问中添加flash属性,框架会在session中记录该属性值
  • 当跳转到页⾯之后框架会⾃动删除flash属性,不需要⼿动删除,通过这种⽅式进⾏重定向参数传递,参数⻓度和安全性都得到了保障,如下:

下面场景,访问handleRedirect后,我们重定向到其他请求,需要携带name参数。

  @RequestMapping("/handleRedirect")
    public String handRedirect(String name, RedirectAttributes redirectAttributes) {
        // return "redirect:handle01?name"+name; // 这种方式实现 缺点容易过长,不安全等
        redirectAttributes.addAttribute("name", name);
        //  addFlashAttribute⽅法设置了⼀个flash类型属性,该属性会被暂存到session中,在跳转到⻚⾯之后该属性销毁
        return "redirect:handle01";
    }

    /**
     * @return 返回模型和视图
     */
    @RequestMapping("handle01")
    public ModelAndView handle01(@ModelAttribute("name") String name) {
        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", name);
        modelAndView.addObject("data", date);
        modelAndView.setViewName("/success");
        return modelAndView;
    }

浏览器地址栏: http://localhost:8080/demo/handleRedirect?name=张三

观察测试结果

image-20221213214516083

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK