重定向时请求参数会丢失,我们往往需要重新携带请求参数,我们可以进⾏⼿动参数拼接如下:
return "redirect:handle01?name=" + name;
get
请求,携带参数⻓度有限制
,参数安全性也不⾼,此时,我们可以使用SpringMVC
提供的flash属性机制
,session
中记录该属性值下面场景,访问
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=张三 观察测试结果