@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。这个模型属性是否从jsp页面中获取值?谁能解释一下这个ModelAttribute的工作原理?
有两种用法 @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";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句