@ModelAttribute 的使用
@ModelAttribute注解可被应用在 方法 或 方法参数 上。
对方法使用 @ModelAttribute 注解:
注解在方法上的@ModelAttribute说明了方法的作用是用于添加一个或多个属性到model上。这样的方法能接受与@RequestMapping注解相同的参数类型,只不过不能直接被映射到具体的请求上。
@ModelAttribute 方法会先被调用
在同一个控制器中,注解了@ModelAttribute的方法实际上会在@RequestMapping方法之前被调用。以下是几个例子:
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelAttributeController {
@ModelAttribute
public void init(Model model) {
System.out.println("@RequestMapping方法");
}
@RequestMapping("/model-attribute")
public String get() {
System.out.println("@ModelAttribute方法");
return "model-attribute";
}
}
控制台输出的结果如下:

无返回值的 @ModelAttribute 方法
一般被 @ModelAttribute 注解的无返回值控制器方法被用来向 Model 对象中设置参数,在控制器跳转的页面中可以取得 Model 中设置的参数:
ModelAttributeController.java:
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelAttributeController {
@ModelAttribute
public void init(Model model) {
model.addAttribute("arg", "model中设置的参数");
}
@RequestMapping("/model-attribute")
public String get() {
return "model-attribute";
}
}
model-attribute.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="text" value=${ arg } />
</body>
</html>
访问路径:http://localhost:8080/model-attribute,页面效果如下:

可以发现,我们在被 @RequestMapping 标注的方法中并没有设置任何参数,但是页面却取得了在 @ModelAtribute 标注的方法设置的参数。由此可知,可以使用 @ModelAttribute 标注的方法来设置其他 @ReqeustMapping 方法的公用参数,这样就不用每一个方法都设置共同的 Model 参数。
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelAttributeController {
@ModelAttribute
public void init(Model model) {
model.addAttribute("arg", "model中设置的参数");
}
@RequestMapping("/model-attribute")
public String get() {
return "model-attribute";
}
@RequestMapping("/demo")
public String demo() {
return "demo";
}
}
在 demo.jsp 和 model-attribute.jsp 中都可以获得名为 "arg" 的 Model 参数。
有返回值的 @ModelAttribute 方法
有返回值的 @ModelAttribute 方法和没有返回值的 @ModelAttribute 方法的区别就是,没有返回值的 @ModelAttribute 方法使用 model.addAttribute(String key, Object value); 来向 Model 中增加参数。而有返回值的 @ModelAttribute 方法则直接将需要增加的参数返回。
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pudding.bean.User;
@Controller
public class ModelAttributeController {
@ModelAttribute
public User init(Model model) {
User user = new User("小明", 18);
return user;
}
@RequestMapping("/model-attribute")
public String get() {
return "model-attribute";
}
}
上面的代码的作用是,向 Model 中增加了 key 为 "user" value 为 user 对象的键值对。这个 user 对象中有 username = "小明",age = 18 的属性。
使用 @ModelAttribute("key") 来显示指定属性名
属性名没有被显式指定的时候又当如何呢?在这种情况下,框架将根据属性的类型给予一个默认名称。举个例子,若方法返回一个User类型的对象,则默认的属性名为"user"。你可以通过设置@ModelAttribute注解的值来改变默认值。当向Model中直接添加属性时,请使用合适的重载方法addAttribute(..)-即,带或不带属性名的方法。
以下代码将会向 Model 中设置一个 key 为 "person" ,value 为 user对象的键值对:
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pudding.bean.User;
@Controller
public class ModelAttributeController {
@ModelAttribute("person")
public User init(Model model) {
User user = new User("小明", 18);
return user;
}
@RequestMapping("/model-attribute")
public String get() {
return "model-attribute";
}
}
@ModelAttribute 和 @RequestMapping 注解在同一个方法上
如果 @ModelAttribute 和 @RequestMapping 注解在同一个方法上,那么代表给这个请求单独设置 Model 参数。此时返回的值是 Model 的参数值,而不是跳转的地址。跳转的地址是根据请求的 url 自动转换而来的。比如下面的例子中跳转页面不是 HelloWorld.jsp 而是 model-attribute.jsp。并且参数只有在 model-attribute.jsp 中能够取得,而 demo.jsp 中不能取得。
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelAttributeController {
@ModelAttribute("message")
@RequestMapping("/model-attribute")
public String init(Model model) {
return "HelloWorld";
}
@RequestMapping("/demo")
public String get() {
return "demo";
}
}
在方法参数上使用 @ModelAttribute 注解:
如上一小节所解释,@ModelAttribute注解既可以被用在方法上,也可以被用在方法参数上。这一小节将介绍它注解在方法参数上时的用法。
数据绑定
注解在方法参数上的@ModelAttribute说明了该方法参数的值将由model中取得。如果model中找不到,那么该参数会先被实例化,然后被添加到model中。在model中存在以后,请求中所有名称匹配的参数都会填充到该参数中。这在Spring MVC中被称为数据绑定,一个非常有用的特性,节约了你每次都需要手动从表格数据中转换这些字段数据的时间。
和 BindingResult 配合使用
使用 @ModelAttribute 进行数据绑定之后,可以使用 BindingResult 来返回数据验证结果。数据验证可以使用 hibernate validation 的 @Valid 标签或者 spring Validator 校验机制的 @Validated 配合 BindingResult 使用。 或者自定义校验器来返回 BindingResult 对象来进行校验。你可以通过Spring的 <errors> 表单标签来在同一个表单上显示错误信息。
@Valid 校验器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petForm";
}
// ...
}
@Validated 校验器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@Validated @ModelAttribute("pet") Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petForm";
}
// ...
}
自定义校验器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
// 自己编写一个校验方法来处理 result 对象
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}
// ...
}
@ModelAttribute 的使用的更多相关文章
- 在SpringMVC中使用@SessionAttributes和@ModelAttribute将数据存储在session域中
今天在我的springMVC项目--图书管理系统中,希望在登录时将登录的Users存在session中,开始是准备在controller中使用Servlet API中的对象,可是一直无法引用,不知道为 ...
- SpringMVC @ModelAttribute注解
/** * 1. 有 @ModelAttribute 标记的方法, 会在每个目标方法执行之前被 SpringMVC 调用! * 2. @ModelAttribute 注解也可以来修饰 ...
- spring @ModelAttribute 注解
@ModelAttribute // 表示请求该类的每个Action前都会首先执行它,也可以将一些准备数据的操作放置在该方法里面. public void setReqAndRes(HttpServl ...
- @ModelAttribute 注解及 POJO入参过程
一.modelattribute注解 @ModelAttribute注解的方法有两种,一种无返回值,一种有返回值,方法的可以用@RequestParam注解来获取请求的参数,如果不获取参数,可以不用此 ...
- SpringMVC常用注解實例詳解2:@ModelAttribute
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- Spring MVC 对于@ModelAttribute 、@SessionAttributes 的详细处理流程
初学 Spring MVC , 感觉对于 @ModelAttribute 和 @SessionAttributes 是如何被Spring MVC处理的,这一流程不是很清楚, 经过Google资料,有了 ...
- Spring MVC 处理模型数据(@ModelAttribute)
SpringMVC中的模型数据是非常重要的,因为MVC中的控制(C)请求处理业务逻辑来生成数据模型(M),而视图(V)就是为了渲染数据模型的数据. 直白来讲,上面这句话的意思就是:当有一个查询的请求, ...
- @ModelAttribute运用详解
@ModelAttribute使用详解 1.@ModelAttribute注释方法 例子(1),(2),(3)类似,被@ModelAttribute注释的方法会在此controller每个 ...
- [Spring MVC] - @ModelAttribute使用
在Spring MVC里,@ModelAttribute通常使用在Controller方法的参数注解中,用于解释model entity,但同时,也可以放在方法注解里. 如果把@ModelAttrib ...
- ModelAttribute注解
1.使用@ModelAttribute标记方法,会在每个目标方法执行前被springMVC调用 2.使用@ModelAttribute修饰目标方法pojo入参,其value属性值有以下作用: 1)sp ...
随机推荐
- Requests库发送post请求,传入接口参数后报JSON parse error
报错信息: {"timestamp":"2020-01-08T14:42:40.894+0000","status":400,"e ...
- python-集合,列表和元组
a = {11,22,33} b = [11,22,33] c = (11,22,33,22) 集合:type(a) -->>set#集合内元素不可重复,花括号括起来的还有 -->& ...
- 题解 P1305 【新二叉树】
好像没有人搞\(\color{green}map\)反映,没有人用\(\color{green}map\)反映搞并查集! \(\color{green}map\)第一个好处是作为一个数组,可以开很大! ...
- 强化学习之二:Q-Learning原理及表与神经网络的实现(Q-Learning with Tables and Neural Networks)
本文是对Arthur Juliani在Medium平台发布的强化学习系列教程的个人中文翻译.(This article is my personal translation for the tutor ...
- Spring - 数据库开发概述
Spring 数据库开发 Spring 的 JDBC 模块负责数据库资源管理和镨误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业 ...
- [POJ2533]Longest Ordered Subsequence<dp>
题目链接:http://poj.org/problem?id=2533 描述: A numeric sequence of ai is ordered if a1 < a2 < ... & ...
- CSS躬行记(2)——伪类和伪元素
一.伪类选择器 伪选择器弥补了常规选择器的不足,能够实现一些特殊情况下的样式,例如在鼠标悬停时或只给字符串中的第一个字符指定样式.与类选择器类似,可以从HTML元素的class属性中查看到,但伪选择器 ...
- VUE一款适用于pc平台的简单toast
新项目要求用typescript+vue+elementui的模式来搭建pc项目,最初踩了好多坑.产品说提示不想用element-ui的提示. 打算用toast的形式.所以就自己写了一个pc的toas ...
- GitHub 热点速览 Vol.15:Background-Matting 让你秒变专业抠图师
作者:HelloGitHub-小鱼干 摘要:如果要选一个词来概述上周的热点,春风拂过,应该是一个不错的词.新项目像春天冒出的枝芽,朝气蓬勃,虽然获得的 star 不如之前三维 Vim 抢眼,但胜在多姿 ...
- Spring(一):Spring入门程序和IoC初步理解
本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接 https://space.bilibili.com/95256449?spm_id_from=33 ...