spring mvc提交日期類型參數


如題,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得到驗證結果了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM