您好,登錄后才能下訂單哦!
這篇文章給大家介紹springboot怎樣重定向攜帶數(shù)據(jù)RedirectAttributes,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
傳統(tǒng)使用session
使用RedirectAttributes. (利用session原理)
優(yōu)點(diǎn):提供了addFlashAttribute 等方法.確保數(shù)據(jù)只能被使用一次后刪除
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è)頁面取出這個(gè)數(shù)據(jù)以后,將session里面的數(shù)據(jù)刪除\
addFlashAttribute 方法會(huì)將數(shù)據(jù)存儲(chǔ)在session中,訪問一次后失效
@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"; }
首先,檢查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; }
關(guān)于springboot怎樣重定向攜帶數(shù)據(jù)RedirectAttributes就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。