SpringMVC之数据存储
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;
}
结果:


浙公网安备 33010602011771号