- 用戶中有日期(Date)屬性,提交表單的時候,SpringMVC報錯,意思是不能把字符串轉為日期類型的,瀏覽器報400。如果是strtus的話,壓根不是問題,這事因為sprongMVC識別不了Data類型解決方式有如下幾種
- 第一種方法:實體類加注解
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date birthday; @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") public Date getBirthday(){
在對應的字段屬性上加注解。
- 第二種方法:控制器中加入一段數據綁定的代碼
//將字符串轉換為Date類 @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { //轉換日期格式 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //注冊自定義的編輯器 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }
- 第三種方法:實現一個全局日期類型轉換器進行配置
package com.xueqing.demo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; public class CustomDateEdtor implements WebBindingInitializer { public void initBinder(WebDataBinder binder, WebRequest request) { // TODO Auto-generated method stub //轉換日期格式 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
然后在springMvc配置文件進行配置
<!-- 配置全局日期轉換器 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="nuc.ss.wlb.core.web.CustomDateEdtor"/> </property> </bean>
- 第四種方法:更改日期輸入框格式
馬虎造成輸入框日期格式與數據庫格式不一致造成,比如我數據庫是這樣的格式:
而你輸入框的格式是這樣的
也會導致因為Date類型不對應造成的400錯誤,所以這時候需把兩邊的格式改為一致才行。