SpringMVC之數據存儲
阿新 • • 發佈:2017-10-02
alt string servle nat 參數 urn row lan map類型
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存儲數據:new ModelAndView(SUCCESS);中的SUCCESS是設置執行完該函數後將要跳轉的頁面。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、將請求參數保存一份到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; }
結果:
SpringMVC之數據存儲