在做web開發的時候,頁面傳入的都是String類型,SpringMVC可以對一些基本的類型進行轉換,但是對于日期類的轉換可能就需要我們配置。
1、如果查詢類使我們自己寫,那么在屬性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd") ,即可將String轉換為Date類型,如下
1
2
|
@DateTimeFormat (pattern = "yyyy-MM-dd" ) private Date createTime; |
2、如果我們只負責web層的開發,就需要在controller中加入數據綁定:
1
2
3
4
5
|
@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:不能為空值 |
3、可以在系統中加入一個全局類型轉換器
實現轉換器
1
2
3
4
5
6
7
8
9
10
11
12
|
public class DateConverter implements Converter<String, Date> { @Override public Date convert(String source) { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); dateFormat.setLenient( false ); try { return dateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } return null ; } |
進行配置:
1
2
3
4
5
6
7
|
< bean id = "conversionService" class = "org.springframework.format.support.FormattingConversionServiceFactoryBean" > < property name = "converters" > < list > < bean class = "com.doje.XXX.web.DateConverter" /> </ list > </ property > </ bean > |
1
|
< mvc:annotation-driven conversion-service = "conversionService" /> |
4、如果將日期類型轉換為String在頁面上顯示,需要配合一些前端的技巧進行處理。
5、SpringMVC使用@ResponseBody返回json時,日期格式默認顯示為時間戳。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Component ( "customObjectMapper" ) public class CustomObjectMapper extends ObjectMapper { public CustomObjectMapper() { CustomSerializerFactory factory = new CustomSerializerFactory(); factory.addGenericMapping(Date. class , new JsonSerializer<Date>() { @Override public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); jsonGenerator.writeString(sdf.format(value)); } }); this .setSerializerFactory(factory); } } |
配置如下:
1
2
3
4
5
6
7
|
< mvc:annotation-driven > < mvc:message-converters > < bean class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" > < property name = "objectMapper" ref = "customObjectMapper" ></ property > </ bean > </ mvc:message-converters > </ mvc:annotation-driven > |
6、date類型轉換為json字符串時,返回的是long time值,如果需要返回指定的日期的類型的get方法上寫上@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") ,即可將json返回的對象為指定的類型。
1
2
3
4
5
|
@DateTimeFormat (pattern= "yyyy-MM-dd HH:mm:ss" ) @JsonFormat (pattern= "yyyy-MM-dd HH:mm:ss" ,timezone = "GMT+8" ) public Date getCreateTime() { return this .createTime; } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/lcngu/p/5785805.html