controller中可以自动接收表单中的数据,但只是一些基本类型,如int,String,char等,若是date类型或其他,则会报错,类型不能转化;
若是只针对单一的controller,可以使用@initBinder注解,让请求到达controller的时候,先进行类型的转换。
示例:
1 .JavaBean(其中timeLimit为date类型)
public class {
private int id;
private String name;
private Date timeLimit;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(Date timeLimit) {
this.timeLimit = timeLimit;
}
}
2 Controller
@Controller
@RequestMapping("user")
public class UserController extends BaseController{
@Resource(name="userService")
private UserService userService;
@RequestMapping(params="add",produces = "application/json; charset=utf-8")
@ResponseBody
public String addUser(User user,HttpServletRequest request){
String result = userService.addUser(user);
return result;
}
/**
* 时间类型转化
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Date.class,"timeLimit",new DateEditor());
}
}
3 DateEditor类:继承PropertyEditorSupport类,重写getAsText()方法和setAsText()方法
public class DateEditor extends PropertyEditorSupport{
@Override
public String getAsText() {
Date date = (Date)getValue();
if(date==null){
date = new Date();
}
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sf.format(date);
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
Date value = null;
if(text!=null&&!text.equals("")){
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
value = sf.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}
}
setValue(value);
}
}