<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
This is my JSP page. <br>
<form action="SpringMvc/testModelAttribute" method="POST">
<input type="hidden" name="id" value="1" /><br>
username:<input type="text" name="username" value="tianxia"/> <br>
age: <input type="text" name="age" value="20" /> <br>
email: <input type="text" name="email" value="[email protected]" /> <br>
<input type="submit" value="Submit" />
</form>
<br><br>
</body>
</html>
package com.atChina.controller;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.atChina.entities.User;
@RequestMapping("/SpringMvc")
@Controller
public class RequestMapperingTest {
/*
* @ModelAttribute 标记的方法,会在每个目标方法执行之前被SpringMVC调用
*/
@ModelAttribute
public void getUser(Map<String, Object> map){
User user = new User("tianxia", "123456789", 1, "[email protected]", 22);
System.out.println("从数据库得到:" + user);
map.put("user", user);
}
/*
* 运行流程
* 1. 执行@ModelAttribute注解修饰的方法
* 2. Spring MVC从map中取出User对象,并把表单的请求参数赋给该User对象的对应属性
* 3. Spring MVC把上述对象传入目标方法的参数
*/
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
System.out.println("修改:" + user);
return "success";
}
}