initBinder是spring自带的,默认使用“/”格式,如“1999/10/10”;当使用“1999-10-10”或“1999.10.10”则要在获取封装参数的类中重写initBinder方法。
package cn.liu.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
import cn.liu.domain.User;
//从页面接收参数,封装Javabean的User对象
public class CommandController extends AbstractCommandController {
//指定把参数封装到User对象
public CommandController() {
setCommandClass(User.class);
}
@Override
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command,
BindException errors) throws Exception {
//值被封装命令对象
User user = (User) command;
//使用ModelAndView回显
ModelAndView mav = new ModelAndView();
//设置model数据,值可以是任意的pojo
mav.addObject("user", user);
//指定返回视图页面
mav.setViewName("index");
return mav;
}
@Override
//获取birthday参数,并使用它的格式
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
String birthday = request.getParameter("birthday");
if (birthday.contains(".")) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy.mm.dd"), true));
}
else if(birthday.contains("/")) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy/mm/dd"), true));
}else {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-mm-dd"), true));
}
}
}