How doe springboot redirect that carrying data RedirectAttributes

  • 2021-11-13 07:51:19
  • OfStack

How does the directory carry data when the controller layer needs to be redirected to a specified page? RedirectAttributes can't be read after using RedirectAttributes memory value

How does the controller layer carry data when it needs to be redirected to a specified page?

Traditional use of session Use RedirectAttributes. (Using session principle) Advantages: addFlashAttribute and other methods are provided. Ensure that data can only be deleted after being used once

Use of 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();
}
Add RedirectAttributes directly to the parameters of Controller. addFlashAttribute will delete the data in session after redirecting to the next 1 page to fetch this data.\ The addFlashAttribute method will store data in session, and it will fail after accessing it once

@PostMapping("/regist")
public String register(RedirectAttributes attribdatautes){
    int data = 1;
    attributes.addFlashAttribute("data",data);
    return "redirect:http://auth.gulimail.com/reg.html";
}
The addAttribute method splices data after 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";
    }

Unable to read after RedirectAttributes stored value

First, check whether Controller is @ Controller or @ RestController (the difference between the two is Baidu)

Secondly, as follows


@GetMapping("/redirect")
public String redirect(RedirectAttributes redirectAttributes)
{
    redirectAttributes.addFlashAttribute("test", 1);
    return "redirect:/show";
}
 
@GetMapping("/show")
@ResponseBody
// You must add @ModelAttribute Tag, no side will not read the value 
// You must specify a variable name and do not automatically match 
public Map<String, Object> show(@ModelAttribute("test") int test)
{
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("String", test);
    return modelMap;
}

Related articles: