正常情況下,前端傳遞來的參數都能直接被SpringMVC接收,但是也會遇到一些特殊情況,比如Date對象,當我的前端傳來的一個日期時,就需要服務端自定義參數綁定,將前端的日期進行轉換。自定義參數綁定也很簡單,分兩個步驟:
1.自定義參數轉換器
自定義參數轉換器實現Converter接口,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class DateConverter implements Converter<String,Date> { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); @Override public Date convert(String s) { if ( "" .equals(s) || s == null ) { return null ; } try { return simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return null ; } } |
convert方法接收一個字符串參數,這個參數就是前端傳來的日期字符串,這個字符串滿足yyyy-MM-dd格式,然后通過SimpleDateFormat將這個字符串轉為一個Date對象返回即可。
2.配置轉換器
自定義WebMvcConfig繼承WebMvcConfigurerAdapter,在addFormatters方法中進行配置:
1
2
3
4
5
6
7
|
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter( new DateConverter()); } } |
OK,如上兩步之后,我們就可以在服務端接收一個前端傳來的字符串日期并將之轉為Java中的Date對象了,前端日期控件如下:
1
2
3
4
5
6
7
8
|
<el-date-picker v-model= "emp.birthday" size= "mini" value-format= "yyyy-MM-dd HH:mm:ss" style= "width: 150px" type= "date" placeholder= "出生日期" > </el-date-picker> |
服務端接口如下:
1
2
3
4
5
6
7
|
@RequestMapping (value = "/emp" , method = RequestMethod.POST) public RespBean addEmp(Employee employee) { if (empService.addEmp(employee) == 1 ) { return new RespBean( "success" , "添加成功!" ); } return new RespBean( "error" , "添加失敗!" ); } |
其中Employee中有一個名為birthday的屬性,該屬性的數據類型是一個Date
原文鏈接:http://blog.csdn.net/u012702547/article/details/79244688