springboot -重定向携带数据 RedirectAttributes

springboot -重定向携带数据 RedirectAttributes

当controller层需要重定向到指定页面时,如何携带数据?

  • 传统使用session
  • 使用RedirectAttributes. (利用session原理)
    • 优点: 提供了addFlashAttribute 等方法.确保数据只能被使用一次后删除

RedirectAttributes的使用

public interface RedirectAttributes extends Model {
    
    
    RedirectAttributes addAttribute(String var1, @Nullable Object var2);

    RedirectAttributes addAttribute(Object var1);

    RedirectAttributes addAllAttributes(Collection<?> var1);

    RedirectAttributes mergeAttributes(Map<String, ?> var1);

    RedirectAttributes addFlashAttribute(String var1, @Nullable Object var2);

    RedirectAttributes addFlashAttribute(Object var1);

    Map<String, ?> getFlashAttributes();
}
  • 直接在Controller的参数中添加RedirectAttributes.

  • addFlashAttribute会在重定向到下一个页面取出这个数据以后,将session里面的数据删除\

  • addFlashAttribute 方法会将数据存储在session中,访问一次后失效

@PostMapping("/regist")
public String register(RedirectAttributes attribdatautes){
    
    
    int data = 1;
    attributes.addFlashAttribute("data",data);
    return "redirect:http://auth.gulimail.com/reg.html";
}
  • addAttribute 方法会将数据拼接在url后(get的形式)
@GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPagez(@RequestParam("skuId") Long skuId,Model model){
    
    
        CartItem cartItem = cartService.selectCartItemInfo(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }

猜你喜欢

转载自blog.csdn.net/weixin_44634197/article/details/108399279