SpringMVC 重定向參數(shù)RedirectAttributes實(shí)例
重定向參數(shù)RedirectAttributes
SpringMVC 中常用到 redirect 來實(shí)現(xiàn)重定向。但使用場景各有需求,如果只是簡單的頁面跳轉(zhuǎn)顯然無法滿足所有要求,比如重定向時(shí)需要在 url 中拼接參數(shù),或者返回的頁面需要傳遞 Model。
SpringMVC 用 RedirectAttributes 解決了這兩個(gè)需要。
1. addAttribute
@RequestMapping("/save") public String save(User user, RedirectAttributes redirectAttributes) { redirectAttributes.addAttribute("param", "value1"); return "redirect:/index"; }
請(qǐng)求 /save 后,跳轉(zhuǎn)至/index,并且會(huì)在url拼接 ?param=value1。
2. addFlashAttribute
@RequestMapping("/save") public String save(User user, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("param", "value1"); return "redirect:/index"; }
請(qǐng)求 /save 后,跳轉(zhuǎn)至 /index,并且可以在 index 對(duì)應(yīng)的模版中通過表達(dá)式,比如 jsp 中 jstl 用 ${param},獲取返回值。該值其實(shí)是保存在 session 中的,并且會(huì)在下次重定向請(qǐng)求時(shí)刪除。
RedirectAttributes 中兩個(gè)方法的簡單介紹就是這樣。
重定向攜帶參數(shù)問題
問題描述
A.jsp發(fā)送請(qǐng)求進(jìn)入Controller,并想重定向到B.jsp并攜帶參數(shù),發(fā)現(xiàn)攜帶的參數(shù)前臺(tái)獲取不到,然后采用以下方法即可
@RequestMapping("/index") public String delete(String id, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("msg","刪除成功!"); return "redirect:hello"; }
@RequestMapping("hello") public String index( @ModelAttribute("msg") String msg) { return "sentinel"; }
首先進(jìn)入delete方法,將msg放在redirectAttributes里,然后重定向到hello,通過@ModelAttribute(“msg”) String msg獲取到msg的值,那么自然sentinel頁面就能獲取到msg的值。
問題來源
B.jsp發(fā)送請(qǐng)求,跳轉(zhuǎn)到A.jsp,并將請(qǐng)求所產(chǎn)生的數(shù)據(jù)攜帶到A頁面。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring聲明式事務(wù)注解之@EnableTransactionManagement解析
這篇文章主要介紹了Spring聲明式事務(wù)注解之@EnableTransactionManagement解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08Springboot整合mybatisplus的項(xiàng)目實(shí)戰(zhàn)
本文主要介紹了Springboot整合mybatisplus的項(xiàng)目實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06Java中volatile關(guān)鍵字的線程的可見性、有序性詳解
這篇文章主要介紹了Java中volatile關(guān)鍵字的線程的可見性、有序性詳解,在juc多線程并發(fā)編程中,常常需要關(guān)注線程的"可見性"與"有序性",本文將詳細(xì)介紹這兩部分內(nèi)容,以及volatile關(guān)鍵字的使用,需要的朋友可以參考下2024-01-01Java實(shí)現(xiàn)人臉識(shí)別登錄、注冊(cè)等功能(最新完整版)
這段時(shí)間由于學(xué)校實(shí)行靜態(tài)化管理,寢室門和校門都是用了人臉識(shí)別的裝置,本系列項(xiàng)目從設(shè)計(jì)到實(shí)現(xiàn)源碼全部開源免費(fèi)學(xué)習(xí)使用,對(duì)Java實(shí)現(xiàn)人臉識(shí)別登錄、注冊(cè)功能感興趣的朋友一起看看吧2022-05-05Java實(shí)現(xiàn)LeetCode(組合總和)
這篇文章主要介紹了Java實(shí)現(xiàn)LeetCode(組合總數(shù)),本文通過使用java實(shí)現(xiàn)leetcode的組合總數(shù)題目和實(shí)現(xiàn)思路分析,需要的朋友可以參考下2021-06-06