Spring MVC中@ModelAttribute的目的和用法是什么?
当前回答
将方法参数或方法返回值绑定到已命名模型属性的注释,暴露在web视图中。
public String add(@ModelAttribute("specified") Model model) {
...
}
其他回答
@ModelAttribute只是将jsp字段的值绑定到Pojo类,以执行控制器类中的逻辑。如果您熟悉struts,那么这就像在提交时填充formbean对象。
@ModelAttribute将使用您指定的名称(@ModelAttribute(“Testing”)Test Test)创建一个属性,在给定的示例中作为Testing,Test是bean测试,是bean的引用,而Testing将在模型中可用,以便您可以进一步在jsp页面上使用它来检索存储在ModelAttribute中的值。
将方法参数或方法返回值绑定到已命名模型属性的注释,暴露在web视图中。
public String add(@ModelAttribute("specified") Model model) {
...
}
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中定义,等等……
推荐文章
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?
- 在Java中使用“final”修饰符
- 无法在Flutter上找到捆绑的Java版本
- 如何在Kotlin解析JSON ?
- 如何在新的材质主题中改变背面箭头的颜色?