SpringMVC重定向隐藏url参数

1.问题引入

问题: 重定向到目标url之后,地址栏带请求参数引发问题

1.用户通过地址栏获取到一些数据

2.用户刷新后仍然在带了请求参数之后的逻辑处理下。

解决方案:通过请求参数加密解密可以解决问题1带来的影响,但是仍然不能解决问题2带来的影响

2.重定向传递参数和取参

1. 传参: 以字符串的形式构建目标url, 可以使用 query variable的格式拼url. 取参: @RequestParam()来fetch
2. 传参: redirectAttributes.addAttribute() 加的attr. 取参: @RequestParam()来fetch
3. 传参: redirectAttributes.addFlashAttribute() 加的attr. 取参: @ModelAttribute()来fetch

3.Flash attribute的特点

 Spring MVC 3.1版本加了一个很有用的特性,Flash属性,它能解决一个长久以来缺少解决的问题,一个POST/Redirect/GET模式问题

1. addFlashAttribute() 可以是任意类型的数据(不局限在String等基本类型), addAttribute()只能加基本类型的参数. 
2. addFlashAttribute() 加的 attr, 不会出现在url 地址栏上.
3. addFlashAttribute() 加的 attr, 一旦fetch后, 就会自动清空, 非常适合 form 提交后 feedback Message.

redirectAttributes.addFlashAttribute()是把参数放在session中 ,跳转之后再从session中移除

4.示例

传值

@RequestMapping("/loginFree")
public String loginFree(HttpServletRequest request, RedirectAttributes attributes)
{
    // 省略     commonLogin();     attributes.addFlashAttribute(
"msg", "哦吼");     return "redirect:/index"; }

取值

// 方式一
@GetMapping("/index")
public String index(ModelMap mmap, @ModelAttribute("msg") String msg) {
  Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
  System.out.println(map.get("msg").toString());
  return "index";
}

// 方式二
@GetMapping("/index")
public String index(ModelMap mmap, @ModelAttribute("msg") String msg) {
  System.out.println(msg);  
  return "index";
}

通过这种方式,就可以解决重定向到目标url,地址栏带请求参数得问题了。

猜你喜欢

转载自www.cnblogs.com/jefferyfeng/p/12714289.html