欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot如何重定向攜帶數(shù)據(jù) RedirectAttributes

 更新時(shí)間:2021年09月15日 17:24:30   作者:彷徨的我第一次嘗試  
這篇文章主要介紹了springboot如何重定向攜帶數(shù)據(jù) RedirectAttributes,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

當(dāng)controller層需要重定向到指定頁(yè)面時(shí),如何攜帶數(shù)據(jù)?

  • 傳統(tǒng)使用session
  • 使用RedirectAttributes. (利用session原理)
  • 優(yōu)點(diǎn):提供了addFlashAttribute 等方法.確保數(shù)據(jù)只能被使用一次后刪除

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的參數(shù)中添加RedirectAttributes.
  • addFlashAttribute會(huì)在重定向到下一個(gè)頁(yè)面取出這個(gè)數(shù)據(jù)以后,將session里面的數(shù)據(jù)刪除\
  • addFlashAttribute 方法會(huì)將數(shù)據(jù)存儲(chǔ)在session中,訪問(wèn)一次后失效
@PostMapping("/regist")
public String register(RedirectAttributes attribdatautes){
    int data = 1;
    attributes.addFlashAttribute("data",data);
    return "redirect:http://auth.gulimail.com/reg.html";
}
  • addAttribute 方法會(huì)將數(shù)據(jù)拼接在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";
    }

RedirectAttributes存值后讀取不到

首先,檢查Controller上面是@Controller還是@RestController(兩者區(qū)別自行百度)

其次,如下

@GetMapping("/redirect")
public String redirect(RedirectAttributes redirectAttributes)
{
    redirectAttributes.addFlashAttribute("test", 1);
    return "redirect:/show";
}
 
@GetMapping("/show")
@ResponseBody
//必須要添加@ModelAttribute標(biāo)簽,否側(cè)將讀不到值
//且必須指定變量名,并不會(huì)自動(dòng)做匹配
public Map<String, Object> show(@ModelAttribute("test") int test)
{
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("String", test);
    return modelMap;
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家?!?/p>

相關(guān)文章

最新評(píng)論