Spring MVC @ModelAttribute注解只支持一个属性value,类型为String,表示绑定的属性名称。被@ModelAttribute注解的方法会在Controller每个方法执行前被执行。
创建UserController
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
/**
* 被@ModelAttribute注解的userModel方法会先于login调用,它把请求参数userName
* 的值赋给userName变量,并设置了一个属性userName到Model中,而属性的值就是userName变量的值
* @param userName
* @return
*/
@ModelAttribute("userName")
public String userModel(@RequestParam("userName")String userName) {
return userName;
}
@RequestMapping("/login")
public String login() {
return "success";
}
}
创建index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<h4>测试@ModelAttribute</h4>
<form action="login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
创建success.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>success</title>
</head>
<body>
用户名:${requestScope.userName }
</body>
</html>
启动Tomcat访问index.jsp
输入用户名,点击【登录】