下面介紹controller向jsp頁面傳遞數據的幾種方式
請求轉發
1.在學習MVC之前,用request的setAttribute方法傳遞數據
@RequestMapping("/response")
public ModelAndView sendData01(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("result");
request.setAttribute("user_name", "清雅軒");
return mav;
}
在jsp頁面用el表達式即可接到數據。
2.用ModelAndView的addObject方法
@RequestMapping("/modelandview")
public ModelAndView sendData02() {
ModelAndView mav = new ModelAndView("result");
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", "1");
map.put("user_name", "清雅軒");
mav.addObject("map", map);
return mav;
}
3.用ModelMap的addAttribute方法
@RequestMapping("/modelmap")
public String sendData03(ModelMap modelMap) {
modelMap.addAttribute("user_name", "清雅軒");
return "result";
}
這里返回值為一個字符串,而不是ModelAndView對象,實際上字符串形式與ModelAndView的viewName等價,解析器也會將字符串解析出路徑。
還有一種返回值為void的形式,這種默認會將@RequestMapping中的請求路徑進行解析得出路徑。
@RequestMapping("/void")
public void voidMethod() {
//默認的返回路徑為/WEB-INF/void.jsp
}
4.用Model的addAttribute方法
@RequestMapping("/model")
public String sendData04(Model model) {
model.addAttribute("user_name", "清雅軒");
return "result";
}
5.用Map集合
@RequestMapping("/map")
public String sendData05(Map<String, String> map) {
map.put("user_name", "清雅軒");
return "result";
}
重定向
1.在路徑后拼湊數據
@RequestMapping("/redirect")
public String sendData06() {
return "redirect:result.jsp?user_name=qingyaxuan";
}
這種方式傳遞的數據屬於param域,用${param.user_name}可以獲取。但是這種方式在地址欄會顯示出參數,而且只能傳遞簡單參數。
2.用RedirectAttribute的addFlashAttribute方法
因為/WEB-INF/的安全級別很高,重定向方式無法訪問/WEB-INF/目錄下的jsp文件,所以需要先重定向到controller中再由請求轉發訪問。
@RequestMapping("/redirect02")
public String sendData07(RedirectAttributes redi) {
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", "1");
map.put("user_name", "qingyaxuan");
redi.addFlashAttribute("map", map);
redi.addFlashAttribute("account", "account");
return "redirect:redirect03";
}
@RequestMapping("/redirect03")
public String sendData08() {
return "result";
}
用addFlashAttribute傳遞的數據屬於request域,可用$(requestScope.account)獲取。
而且這種方式可以傳遞復雜數據類型。
使用addFlashAttribute方法傳值是為了解決下列問題,引用別人的解釋說明一下:
正常的MVC Web應用程序在每次提交都會POST數據到服務器。一個正常的Controller (被注解 @Controller標記)從請求獲取數據和處理它 (保存或更新數據庫)。一旦操作成功,用戶就會被帶到(forward)一個操作成功的頁面。傳統上來說,這樣的POST/Forward/GET模式,有時候會導致多次提交問題. 例如用戶按F5刷新頁面,這時同樣的數據會再提交一次。
為了解決這問題, POST/Redirect/GET 模式被用在MVC應用程序上. 一旦用戶表單被提交成功, 我們重定向(Redirect)請求到另一個成功頁面。這樣能夠令瀏覽器創建新的GET請求和加載新頁面。這樣用戶按下F5,是直接GET請求而不是再提交一次表單。
雖然這一方法看起來很完美,並且解決了表單多次提交的問題,但是它又引入了一個獲取請求參數和屬性的難題. 通常當我們生成一次http重定向請求的時候,被存儲到請求數據會丟失,使得下一次GET請求不可能訪問到這次請求中的一些有用的信息.
Flash attributes 的到來就是為了處理這一情況. Flash attributes 為一個請求存儲意圖為另外一個請求所使用的屬性提供了一條途徑. Flash attributes 在對請求的重定向生效之前被臨時存儲(通常是在session)中,並且在重定向之后被立即移除。
但引述的說法中,數據是被存在session中的,我試的例子中數據是存在request域中的,不知究竟孰是孰非,有知道的dalao希望能指點迷津。
