版权声明:本文为博主原创作品,如需转载请标明出处。 https://blog.csdn.net/weixin_42162441/article/details/82824441
跨重定向请求传递数据
方法有二:
- 使用 URL 模板以路径变量和/或查询参数的形式传递数据;
- 通过 flash 属性发送数据。
通过 URL 模板进行重定向
在创建 URL 的时候,直接使用 String 拼接是很危险的,建议使用模板的方式来定义重定向 URL。
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(
@RequestParam(value="username") String username,
@RequestParam(value="password") String password,
Model model) {
User user = userService.getUser(username);
if(user.getPassword().equals(password)) {
model.addAttribute("username", username);
return "redirect:/index/{username}";
}
return "redirect:/";
}
现在,username 作为占位符填充到了 URL 模板中,而不是直接连接到重定向 String 中,所以所有的不安全字符都会进行转义。这样更安全。
另外,模型中所有其他的原始类型都可以添加到 URL 中作为查询参数。
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(
@RequestParam(value="username") String username,
@RequestParam(value="password") String password,
Model model) {
User user = userService.getUser(username);
if(user.getPassword().equals(password)) {
model.addAttribute("username", username);
model.addAttribult("password", password);
return "redirect:/index/{username}";
}
return "redirect:/";
}
模型中的 password 属性没有匹配重定向 URL 中的任何占位符,所以它会自动以查询参数的形式附加到重定向 URL 上。
使用 flash 属性
在想要发送复杂的对象时使用。
有一种方法就是放在 Session 中,而在 Spring 中,提供了将数据发送为 flash 属性的功能。按照定义, flash 属性会一直携带这些数据直到下一次请求,然后才会消失。
Spring 提供了通过 RedirectAttributes 设置 flash 属性的方法。是 Model 的一个子接口。
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(
@RequestParam(value="username") String username,
@RequestParam(value="password") String password,
RedirectAttributes model) {
User user = userService.getUser(username);
System.out.println(password);
if(user.getPassword().equals(password)) {
model.addFlashAttribute("user", user);
return "redirect:/index";
}
return "redirect:/";
}
在重定向前将对象复制到会话中,重定向后,取出。