当前位置:网站首页>重定向设置参数-RedirectAttributes

重定向设置参数-RedirectAttributes

2022-06-13 02:19:00 liangjiayy

API位置:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html#:~:text=A RedirectAttributes model is empty when the method,of the controller that serves the target URL.

基本使用:

 @RequestMapping(value = "/accounts", method = RequestMethod.POST)
 public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
    
   if (result.hasErrors()) {
    
     return "accounts/new";
   }
   // 重定向设置属性
   redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
   return "redirect:/accounts/{id}";
 }

有两种方式:(一般使用addFlashAttribute,另一种数据在地址栏,用户可见,不安全)

  • addAttribute:重定向后在url后面拼上参数;本质上是根据您的属性构造请求参数,然后使用请求参数重定向到所需的页面,即:key1=val1&key2=val2…
    使用:
    // 不转为json,报错:Cannot convert value of type 'java.util.HashMap' to required type 'java.lang.String'
    Map<String,String> val=new HashMap<>();
    ...
    redirectAttributes.addAttribute("key", JSONObject.toJSONString(val));
    
  • addFlashAttribute:放在session中,第一次使用后将删除
    使用
    Map<String,String> val=new HashMap<>();
    ...
    redirectAttributes.addFlashAttribute("key", val);
    
原网站

版权声明
本文为[liangjiayy]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_55155505/article/details/125251148