Spring MVC重定向参数传递
1.查询参数形式
这种方式直接将参数拼接到url后,发起GET请求;若是对传输数据安全要求比较高则不建议这种方式
/**
* 测试拼接url传参
*
* @param userId 用户id
* @return 重定向url
* @throws Exception
* @date 2017年9月14日
*/
@RequestMapping("/urlParam")
public String urlParam(@RequestParam("userId") Long userId) throws Exception {
return "redirect:/user/getUseInfo.do?userId=" + userId;
}
/**
* 获取用户信息
*
* @param userId 用户id
* @return 重定向url
* @throws Exception
* @date 2017年9月14日
*/
@RequestMapping("/getUserInfo")
public String getUserInfo(@RequestParam("userId") Long userId) throws Exception {
User user = userService.findById(userId);
...
}
(1).这种方式通过路径参数方式传递,此时userId作为占位符填充到URL模板中;还有一种方式是直接拼接userId,return ".../user/" + userId + ".do"。
按照<<>Spring 实战>中说法,不推荐拼接的方式,当构建URL或SQL查询语句的时候,使用String连接不安全
(2).接收方法通过@PathVariable注解获取路径中的参数
/**
* 测试URL模板传参
*
* @param model
* @param userId 用户id
* @return
* @throws Exception
* @date 2017年9月14日
*/
@RequestMapping("/urlTemplate")
public String urlTemplate(Model model, @RequestParam("userId") Long userId) throws Exception {
model.addAttribute("userId", userId);
return "redirect:/user/{userId}.do";
}
@RequestMapping("/{userId}")
public String getUserInfo(@PathVariable("userId") Long userId) throws Exception {
User user = userService.findById(userId);
...
}
3.使用flash属性
(1).这种方式类似于将参数存放到会话(Session)中,这样在重定向后得以保存之前的数据。Spring也是这么做的,flash属性会一直保存这些数据直到下一次请求,然后才会消失
(2).Spring提供RedirectAttributes设置flash属性,该接口继承了Model,所以也会拥有Model所有功能。具体通过addFlashAttribute()方法设置flash属性
/**
* 测试flash属性
*
* @param model
* @param userId 用户id
* @return 重定向url
* @throws Exception
* @date 2017年9月14日
*/
@RequestMapping("/flash")
public String flash(RedirectAttributes model, @RequestParam("userId") Long userId) throws Exception {
model.addFlashAttribute("userId", userId);
return "redirect:/user/getUserInfo.do";
}
@RequestMapping("/getUserInfo")
public String getUserInfo(@ModelAttribute("userId") Long userId) throws Exception {
User user = userService.findById(userId);
...
}