mvc Java里model_java - Spring MVC中的@ModelAttribute是什么?

我知道我迟到了,但我会像他们说的那样引用,“最好迟到而不是”。 让我们开始吧每个人都有自己的方式来解释事情,让我尝试总结一下,并通过一个例子在几个步骤中为你简单化;假设你有一个简单的表单form.jsp

First Name :

Last Name :

路径=“名字”路径=“姓氏”这些是StudentClass中的字段/属性当调用表单时,调用它们的getter但是一旦提交它们就会调用它们的setter,并且它们的值是在form标签中的modelAttribute =“student”中指示的bean中设置的。

我们有StudentController,包括以下方法;

@RequestMapping("/showForm")

public String showForm(Model theModel){ //Model is used to pass data between

//controllers and views

theModel.addAttribute("student", new Student()); //attribute name, value

return "form";

}

@RequestMapping("/processForm")

public String processForm(@ModelAttribute("student") Student theStudent){

System.out.println("theStudent :"+ theStudent.getLastName());

return "form-details";

}

//@ModelAttribute("student") Student theStudent

//Spring automatically populates the object data with form data all behind the

//scenes

现在终于有了一个form-details.jsp

Student Information

${student.firstName}

${student.lastName}

那么回到问题什么是Spring MVC中的@ModelAttribute?来自您的来源的样本定义,[http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation]@ModelAttribute是一个注释,它将方法参数或方法返回值绑定到命名的模型属性,然后将其公开给Web视图。

实际发生的是它获取由它提交的ur表单的所有值,然后保存它们以便绑定或将它们分配给对象。它与@RequestParameter一样,我们只获取一个参数并将值赋给某个字段。唯一的区别是@ModelAttribute保存所有表单数据而不是单个参数。 它为您创建一个bean,用于保存表单提交的数据,供开发人员稍后使用。

回顾整个事情。步骤1 :发送一个请求,我们的方法showForm运行,一个模型,一个临时bean设置名称student转发到表单。theModel.addAttribute(“student”,new Student());

第2步 :的ModelAttribute=“学生”在表单提交模型上更改学生,现在它保存表单的所有参数

第3步:@ModelAttribute(“学生”)学生theStudent我们获取@ModelAttribute所持有的值,并将整个bean /对象分配给Student。

第4步 :然后我们在出价时使用它,就像在页面上显示它一样,就像我一样

我希望它能帮助你理解这个概念。 谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值