由@ModelAttribute标记的方法会在每个目标方法执行之前被SpringMVC调用
可以在提交表单时从数据库中取出数据,然后使用表单数据更新
在java文件中:
写一个User类:
package springmvc;
public class User {
private Integer id;
private String username;
private String password;
private String email;
private int age;
public User(Integer id, String username, String password, String email,
int age) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", email=" + email + ", age=" + age + "]";
}
}
在方法处理类中:
package springmvc;
import java.util.Map;
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;
import springmvc.User;
@Controller
@RequestMapping("/springmvc")
public class HelloWorld {
private static final String SUCCESS = "success";
@ModelAttribute
public void getUser(@RequestParam(value="id", required=false) Integer id,
Map<String, Object> map) {
if (id != null) {
//模拟访问数据库
User user = new User(1, "Tom", "123456", "tom@qq.com", 12);
System.out.println("从数据库中获取一个对象: " + user);
map.put("user", user);
}
}
@RequestMapping("/testModelAttribute")
//public String testModelAttribute(@ModelAttribute("user") User user) {
public String testModelAttribute(User user) {
System.out.println("修改: " + user);
return SUCCESS;
}
}
在index.jsp中:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>SpringMVC</title>
</head>
<body>
<!--
模拟修改操作
1.原始数据为:1,Tom,123456,tom@qq.com,12
2.密码不能修改
3.表单回显,模拟操作直接在表单填写对应的属性值
-->
<form action="springmvc/testModelAttribute" method="post">
<input type="hidden" name="id" value="1"/>
username: <input type="text" name="username" value="Tom"/>
<br>
email: <input type="text" name="email" value="tom@qq.com">
<br>
age: <input type="text" name="age" value="12">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
运行起来可以看到效果:
可以看到成功修改了age属性