本文介绍在 Spring MVC 中非常重要的注解 @ModelAttribute,用来将请求参数绑定到 Model 对象。
在 Controller 中使用 @ModelAttribute 时,有以下几种应用情况。
应用在方法上
应用在方法的参数上
应用在方法上,并且方法也使用了 @RequestMapping
需要注意的是,因为模型对象要先于 controller 方法之前创建,所以被 @ModelAttribute 注解的方法会在 Controller 每个方法执行之前都执行。因此一个 Controller 映射多个 URL 时,要谨慎使用。
- 应用在方法上
下面从应用在有无返回值的方法上两个方面进行讲解。
1)应用在无返回值的方法
示例 1:创建 ModelAttributeController,代码如下。
package net.biancheng.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 org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ModelAttributeController {
// 方法无返回值
@ModelAttribute
public void myModel(@RequestParam(required = false) String name, Model model) {
model.addAttribute(“name”, name);
}
@RequestMapping(value = “/model”)
public String model() {
return “index”;
}
}
创建 index.jsp 页面,代码如下。
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>