@ModelAttribute注解用于将请求的参数绑定到Model对象中,方便在前台的数据回显
@ModelAtttribute注解一个方法的具体的形参
@RequestMapping(value="/updateItem",method=RequestMethod.POST)
public String updateItem(@ModelAttribute("id") Integer id,@ModelAttribute("item")Items itemcustomer) throws Exception{
itemsService.updateItems(id,itemcustomer);
/*model.addAttribute("id",id);*/
return "editItem";
// return "redirect:queryItems.action";
}
- springmvc会自动的将pojo类型添加到Model中,key为该pojo的类名首字母小写
在这里如果去掉形参itmecustomer上的注解,就会由springmvc自动将itemcustomer写到model中,类似于model.addAttribute(“itmes”,itemcustomer), - 如果想要改变Key的值,就必须使用@ModelAttribute(value=key)这个注解
- 对于普通类型springmvc并不会这么做,必须手动编写model.addAttribute(“”),例如这里的id是Integer类型的,所以并不会自动将id写到Model中,除非加上@ModelAttribute(“id”)或者在方法内model.addAttribute(“id”,id)
@ModelAtttribute注解一个方法
@RequestMapping("/queryItems")
public ModelAndView queryItems() throws Exception{
List<ItemsCustomer> itemsCustomers = itemsService.queryItems(null);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("itemsList");
modelAndView.addObject("items",itemsCustomers);
return modelAndView;
}
@ModelAttribute
public Items getItem(Integer id){
Items items = new Items();
items.setName("自己添加的");
return items;
}
- 如果方法返回pojo对象,那么可以不用在@ModelAttribute中加上value属性,其值就是返回类型的首字母小写
- 如果方法没有返回值,那么就可以在方法的形参中加上一个Model形参,然后在代码里就行addAttribute
- 如果方法返回的是普通类型,那么可以在注解里面加上value属性,指定model中的key值
- 在一个Controller类中,如果有方法使用了@ModelAttribute注解,那么每一个请求都会先请求这个方法,然后再请求url指定的那个方法,像上面的这个方法,如果此时请求queryItems.action,那么会调用getItem方法,这个方法会将items以(“items”,items)的形式添加到Model中,然后再执行queryItems方法,不过此时,在这个里面也有这个方法modelAndView.addObject(“items”,itemsCustomers);意味着key重复了,本质上Model是一个Map,所以理所当然的会将之前的items冲掉了
- 使用@ModelAttribute将公用的获取数据的方法返回值传到页面,不用在每一个controller方法通过Model将数据传到页面。
@ModelAtttribute和@RequestMapping方法作用于同一个方法
@RequestMapping("/login")
@ModelAttribute("loginname")
public String login(){
return "admin";
}
- 当使用@RequestMapping和@ModelAtribute一起注解一个方法的时候,方法的返回值是会将加入到Model中的
- 视图名应该是@RequestMapping的value的值,这里就是login
- 请求的时候也是按照@RequestMapping的value进行请求,在这里就是http://localhost:8080/ssmusemaven/login.action