如題,spring mvc直接提交Date類型參數會報錯,400 bad request的錯誤。在controller里加上
@InitBinder protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); CustomDateEditor dateEditor = new CustomDateEditor(format, true); binder.registerCustomEditor(Date.class, dateEditor); super.initBinder(request, binder); }
或
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:允許輸入空值,false:不能為空值 }
可以解決這個問題。但是這個時候Date類型的參數是null的話,還是會報錯。
采用另外一種方式則更好,為null也不會報錯,就是把請求參數封裝為一個vo類,在對應的類屬性上加上注解,這樣
@DateTimeFormat(iso = ISO.DATE_TIME, pattern = "w:yyyy") private Date startTime;
或者
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date lastLoginDate;
另外如果使用驗證框架,方法參數這樣寫(@Valid XxxParam param, BindingResult binding) ,就能直接通過BindingResult得到驗證結果了。