Spring MVC 跨重定向请求传输数据

跨重定向请求传递数据

方法有二:

  • 使用 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:/";
	}

在重定向前将对象复制到会话中,重定向后,取出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值