@RequestMapping(value="/addpost",method=RequestMethod.POST)
public ModelAndView addpost(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("r") Reg reg)
{
int id=r.id;
System.out.println(id);
return mv;
}
在这段代码中,给出了@ModelAttribute(“r”)Reg reg.Wether这个modelattribute是从jsp页面获取值?有人能解释这个ModelAttribute的工作吗?
答案 0 :(得分:0)
@ModelAttribute
在方法级别
在方法级别使用注释时,它表示该方法的目的是添加一个或多个模型属性。此类方法支持与@RequestMapping方法相同的参数类型,但不能直接映射到请求。
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg", "Welcome to the Netherlands!");
}
在该示例中,方法将名为msg的属性添加到控制器类中定义的所有模型。
作为方法论据
当用作方法参数时,它表示应从模型中检索参数。如果不存在,则应首先对其进行实例化,然后将其添加到模型中,并且一旦出现在模型中,就应从所有具有匹配名称的请求参数中填充参数字段。
在随后的代码片段中,员工模型属性中填充了提交给addEmployee端点的表单中的数据。
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
// Code that uses the employee object
return "employeeView";
}