本文介绍在 Spring MVC 中非常重要的注解 @ModelAttribute,用来将请求参数绑定到 Model 对象。
以上示例,在请求 /model?name=%E7%BC%96%E7%A8%8B%E5%B8%AE 后,Spring MVC 会先执行 myModel 方法,将 name 的值存入到 Model 中。然后执行 model 方法,这样 name 的值就被带到了 model 方法中。
将 myModel 和 model 方法合二为一后,代码如下。
@RequestMapping(value = "/model")
public String model(@RequestParam(required = false) String name, Model model) {
model.addAttribute("name", name);
return "index";
}
2)应用在有返回值的方法
示例 2:修改 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("name")
public String myModel(@RequestParam(required = false) String name) {
return name;
}
@RequestMapping(value = "/model")
public String model() {
return "index";
}
}
修改 index.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>编程帮</title>
</head>
<body>
${string }
</body>
</html>
访问地址和运行结果与示例 1 相同。
对于以上情况,返回值对象 name 会被默认放到隐含的 Model 中,在 Model 中 key 为返回值首字母小写,value 为返回的值。等同于 model.addAttribute("string", name);。
大型站长资讯类网站! https://www.nzzz.com.cn