1、使用request域對象存儲數據:將請求中的參數存儲在request中,使用setAttribute()方法可以在jsp頁面訪問該屬性。
@RequestMapping("/test17")
public String test17(HttpServletRequest request String name) throws IOException {
request.setAttribute("name", name);
return SUCCESS;
}
2、使用session域對象存儲數據:
// 存儲數據:session
@RequestMapping("/test18")
public String test18(HttpSession session, String name) throws IOException {
session.setAttribute("name", name);
return SUCCESS;
}
3、使用ModelAndView存儲數據,有兩個作用:
作用一:設置轉向地址,如下所示(這也是ModelAndView和ModelMap的主要區別)
ModelAndView view = new ModelAndView("path:ok");
作用二: 用於傳遞控制方法處理結果數據到結果頁面,也就是說我們把需要在結果頁面上需要的數據放到ModelAndView對象中即可,他的作用類似於request對象的setAttribute方法的作用,用來在一個請求過程中傳遞處理的數據。通過以下方法向頁面傳遞參數:
addObject(String key,Object value);
在頁面上可以通過el表達式$key或者bboss的一系列數據展示標簽獲取並展示ModelAndView中的數據。ModelAndView既可以存儲八大基本類型的數據,也可以存儲List、Set、Map類型的集合。
// 存儲數據:ModelAndView
@RequestMapping("/test19")
public ModelAndView test19(String name) throws IOException {
ModelAndView mav = new ModelAndView(SUCCESS);
ArrayList<String> list = new ArrayList<String>();
list.add("Anna");
list.add("Jay");
list.add("Joe");
list.add("John");
mav.addObject("list", list);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 12);
map.put("b", 23);
map.put("c", 34);
mav.addObject("map", map);
mav.addObject("name", name);
return mav;
}
4、使用Model對象存儲數據
// 存儲數據:Model
@RequestMapping("/test20")
public String test20(Model model) {
model.addAttribute("name", "任我行");
ArrayList<String> list = new ArrayList<String>();
list.add("Anna");
list.add("Jay");
list.add("Joe");
list.add("John");
model.addAttribute("list", list);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 12);
map.put("b", 23);
map.put("c", 34);
model.addAttribute("map", map);
return SUCCESS;
}
5、使用Map存儲數據
// 存儲數據:Map
@RequestMapping("/test21")
public String test21(Map<String, Object> map) {
map.put("name", "任我行");
ArrayList<String> list = new ArrayList<String>();
list.add("Anna");
list.add("Jay");
list.add("Joe");
list.add("John");
map.put("list", list);
return SUCCESS;
}
6、使用ModelMap存儲數據:
ModelMap對象主要用於傳遞控制方法處理數據到結果頁面,也就是說我們把結果頁面上需要的數據放到ModelMap對象中即可,他的作用類似於request對象的setAttribute方法的作用,用來在一個請求過程中傳遞處理的數據。通過以下方法向頁面傳遞參數:
addAttribute(String key,Object value);
在頁面上可以通過el表達式$key或者bboss的一系列數據展示標簽獲取並展示modelmap中的數據。 modelmap本身不能設置頁面跳轉的url地址別名或者物理跳轉地址,那么我們可以通過控制器方法的返回值來設置跳轉url地址別名或者物理跳轉地址。
// 存儲數據:使用ModelMap存儲數據
@RequestMapping("/test23")
public String test23(String name, Integer age, ModelMap model) {
model.addAttribute("name", name);
model.addAttribute("age", age);
return SUCCESS;
}
6、將請求參數保存一份到session當中
在類上加上注解:@SessionAttributes
@SessionAttributes(names={"name", "age"}, types={String.class, Integer.class})
方法代碼:
// 存儲數據:將請求參數保存一份到session當中
@RequestMapping("/test22")
public String test22(String name, Integer age, ModelMap model) {
return SUCCESS;
}
結果:

