最近剛學完 spring mvc ,遇到一個問題。就是當我表單有日期類型的數據(如出生日期)提交到後臺控制器時;就發生了400error;400error用簡短的話來說就是請求參數類型和後臺接收參數類型對不上等。
我大概一猜就知道是因爲日期類型參數的問題;下面總結了一些處理 springMVC 在接收date類型參數的處理。
====方法one
我們後臺的參數用String先接收,再把string轉成date。/**
* 新增員工
*
* @param empVo
* @return 返回成功標識
*/
@RequestMapping("/empAdd")
@ResponseBody //hireday 是前臺表單傳過來的日期
public String empAdd(EmpVo empVo, String hireday) {
//把字符串日期轉成date格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition position1 = new ParsePosition(0);
Date hiredayDate = format.parse(hireday, position1);
//分別是入職日期和出生日期
empVo.setHireDay(hiredayDate);
// DateHelper.parseString(StringHelper.getBirAgeSex(empVo.getCardno()).get("birthday")
// 通過身份證獲取出生日期
empVo.setBirthday( DateHelper.parseString(StringHelper.getBirAgeSex(empVo.getCardno()).get("birthday"),"yyyy-MM-dd"));
//狀態
empVo.setStatus(1);
//默認密碼
empVo.setPassword("123456");
emp.save(empVo);
return "success";
}
====方法two
實體類中加日期格式化註解
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date hireDay;//入職日期
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
public Date getHireDay() {
return hireDay;
}
====方法three(推薦)
控制器加入日期數據綁定方法
//將字符串轉換爲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));
}
====方法four
實現全局日期類型轉換器並進行配置
設計日期轉換類
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 DateEdtor 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));
}
}
在spring MVC配置文件進行配置
<!-- 配置全局日期轉換器 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="nuc.ss.wlb.core.web.DateEdtor"/>
</property>
</bean>