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,地址欄帶請求參數得問題了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM