springmvc Controller類中需要接收的是Date類型,但是在頁面端傳過來的是String類型,就會出現以下異常
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date';
這裏提供三種解決方案。
一.局部轉換
@Controller
@RequestMapping("order")
public class OrderCtrl extends CtrlSupport {
private static final Logger logger = LoggerFactory.getLogger(OrderCtrl.class);
// 將字符串轉換爲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));
}
}
二.全局轉換
1.創建convertDate類實現WebBindingInitializer接口
public class convertDate implements WebBindingInitializer{
@Override
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));
}
}
2.在Spring-MVC.xml中配置日期轉換
<!-- 日期轉換 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.wx.web.convertDate"/>
</property>
</bean>
三.get方法配置
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")
public Date getGetLicenseTime() {
return getLicenseTime;
}
public void setGetLicenseTime(Date getLicenseTime) {
this.getLicenseTime = getLicenseTime;
}
@JsonFormat 默認是標準時區的時間, 北京時間 東八區 timezone=”GMT+8”
作用:後臺的時間 格式化 發送到前臺
@DateTimeFormat 接受前臺的時間格式 傳到後臺的格式