User对象:
package login;
import java.text.SimpleDateFormat;
import java.util.Date;
public class User {
private String userName;
private String password;
private int age;
private Date date;
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 Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "userName:"+this.userName +",password:"+ this.password +",age:"+this.age+",date;"+ new SimpleDateFormat("yyyy-MM-dd").format(this.date);
}
}
controller
package login;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.WebRequestDataBinder;
@Controller
@RequestMapping("/login")
public class Login {
@RequestMapping(value = "/login1",method = RequestMethod.GET)
public String loginGet(){
System.out.println("get");
return "login";
}
@RequestMapping(value = "/login1",method = RequestMethod.POST)
public String loginPost(User user ,BindingResult result){
//提交form 时 自动注入 User 对象 但只能接收 String , int 类型的数据。
//如果要接收 Date 类型的数据就得用下面的 数据绑定 。
System.out.println(user);
return "redirect:/login/succer.do";
}
@RequestMapping(value = "/succer")
public String succer(){
System.out.println("重定向了");
return "login_succer";
}
//数据绑定
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//CustomDateEditor 可以换成自己定义的编辑器。
//注册一个Date 类型的绑定器 。
}
}