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
@RequestMapping(value = "/users")
public class SpareController {
@ModelAttribute(value = "spare")
public String index(@RequestParam String userName) {
System.out.println("进去1");
return userName;
}
@RequestMapping(value = "/home")
public String home() {
System.out.println("进去2");
return "add";
}
}
index方法@ModelAttribute注解上定义一个value为spare,在项目里进入指定的url系统会加载@ModelAttribute的注解给它Map<String,?>定义一个key和value,就是给它添加了个map.put("userName",userName) key键就是@ModelAttribute定义的value,值就是index参数里的userName。然后直接进入到url指定的方法中,跳转到指定view中。
首先我们先定义一个JSP的页面进入到里面,看它执行的是那个方法
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello userName</title>
</head>
<body>
<form action="users/home">
请输入您的姓名:<input name="userName" type="text"/><br>
<input type="submit" value="提交">
</form>
</body>
</html>

index.png
url路径是:(http://localhost:8080/SpringMVC/users/home?userName=hello)

先执行那个方法.png
可以看到我们先执行的方法是index而不是我们直接进入的home的方法,因为在基础controller中用@ModelAttribute修饰一个方法,就可以做到在执行所有的方法之前,先执行这个方法。
跳转到home的页面,${userName} 就是我们@ModelAttribute定义的key,可以通过这个key拿到的value。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello home</title>
</head>
<body>
userName:${userName}
</body>
</html>

home.png