Spring MVC中@ModelAttribute的目的和用法是什么?
当前回答
@ModelAttribute只是将jsp字段的值绑定到Pojo类,以执行控制器类中的逻辑。如果您熟悉struts,那么这就像在提交时填充formbean对象。
其他回答
将方法参数或方法返回值绑定到已命名模型属性的注释,暴露在web视图中。
public String add(@ModelAttribute("specified") Model model) {
...
}
对于我的风格,我总是使用@ModelAttribute从spring form jsp捕获对象。例如,我在jsp页面上设计表单,该表单存在commandName
<form:form commandName="Book" action="" methon="post">
<form:input type="text" path="title"></form:input>
</form:form>
我在控制器上用跟随代码捕获对象
public String controllerPost(@ModelAttribute("Book") Book book)
book的每个字段名必须与form子元素中的path匹配
@ModelAttribute只是将jsp字段的值绑定到Pojo类,以执行控制器类中的逻辑。如果您熟悉struts,那么这就像在提交时填充formbean对象。
ModelAttribute注释被用作Spring MVC Web应用程序的一部分,可以在两种场景中使用。
首先,它可以用于将数据注入到预jsp加载模型中。这在确保需要JSP来显示所有数据本身时特别有用。注入是通过将一个方法连接到模型来获得的。
其次,它可以用于从现有模型中读取数据,并将其分配给教练方法的参数。
具有一定https://dzone.com/articles/using-spring-mvc%E2%80%99s
所以我会试着用更简单的方式来解释。让我们有:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
正如Spring MVC文档中所描述的那样——@ModelAttribute注释可以用于方法或方法参数。当然我们可以在一个控制器中同时使用这两种方法。
1.方法注释
@ModelAttribute("cities")
public List<String> checkOptions(){
return new Arrays.asList(new[]{"Sofia","Pleven","Ruse"});//and so on
}
这种方法的目的是在模型中添加属性。因此,在我们的案例中,cities key将拥有列表new Arrays.asList(new[]{"Sofia","Pleven","Ruse"})作为模型中的值(您可以将模型看作map(key:value))。在同一个控制器中,在@RequestMapping方法之前调用控制器中的@ModelAttribute方法。
在这里,我们希望向Model添加将在表单中用于显示给用户的公共信息。例如,它可以用来填充HTML选择:
2.方法参数
public String findPerson(@ModelAttriute(value="person") Person person) {
//..Some logic with person
return "person.jsp";
}
An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. So in this case we expect that we have in the Model person object as key and we want to get its value and put it to the method argument Person person. If such does not exists or (sometimes you misspell the (value="persson")) then Spring will not find it in the Model and will create empty Person object using its defaults. Then will take the request parameters and try to data bind them in the Person object using their names.
name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&
我们有了name,它会使用setName(String name)绑定到person。name。因此,在
//..Some logic with person
我们可以访问这个值为“Dimitrij”的填充名称。
当然,Spring可以绑定更复杂的对象,比如List、map、List Of Sets Of Maps等等,但在幕后,它实现了数据绑定的魔力。
我们可以同时拥有带模型注释的方法和参数中带有@ModelAttribute的请求方法处理程序。那我们就得统一规则。 当然,我们有很多不同的情况——@ModelAttribute方法也可以在@ControllerAdvice中定义,等等……
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap