RedirectAttributes 的使用

因为使用重定向的跳转方式的情况下,跳转到的地址无法获取 request 中的值。RedirecAtrributes 很好的解决了这个问题。 1. redirectAttributes.addAttributie("param", value); 这种方法相当...

因为使用重定向的跳转方式的情况下,跳转到的地址无法获取 request 中的值。RedirecAtrributes 很好的解决了这个问题。

1. redirectAttributes.addAttributie("param", value);

这种方法相当于在重定向链接地址追加传递的参数。以上重定向的方法等同于 return "redirect:/hello?param=value" ,注意这种方法直接将传递的参数暴露在链接地址上,非常的不安全,慎用。

2. redirectAttributes.addFlashAttributie("param", value);

这种方法是隐藏了参数,链接地址上不直接暴露,但是能且只能在重定向的 “页面” 获取 param 参数值。其原理就是将设置的属性放到 session 中,session 中的属性在跳到页面后马上销毁

注意:这种方式在页面中可以正常获取,但是跳转目标是控制器方法的情况下,需要使用 @ModelAttribute 注解绑定参数后才能获取。

package com.pudding.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class RedirectController {

	@RequestMapping("/set-flash-attribute")
	public String setFlashAttribute(RedirectAttributes redirectAttribute) {
		redirectAttribute.addFlashAttribute("username", "jack");
		return "redirect:/user-information";
	}

	@RequestMapping("/user-information")
	public String get(@ModelAttribute("username") String username) {

		System.out.println(username);

		return "/user-information";
	}

}
  • 发表于 2020-04-26 08:22
  • 阅读 ( 171 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除