spring mvc日期轉換(前端到后端,后端到前端)


在做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;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

 

 

通過注解來協助SpringMVC處理日期在前后端的傳遞問題

從前端向后端傳遞日期:

@DateTimeFormat(pattern="yyyy-MM-dd")

前台向后台傳遞字符串類型的日期參數時,需要通過此注解將字符串解析成日期類型,其中日期格式可以根據需要進行設置。

例子:如果后台接收的createDate為Java.util.Date類型,但前台傳遞過來的是2016-05-23,那么此時我們需要使用@DateTimeFormat注解來修飾createDate字段,否則SpringMVC認為傳遞過來的是字符串與日期類型不匹配而報400錯誤(HTTP Status 400 The request sent by the client was syntactically incorrect)。

 

從后端向前端傳遞日期:

@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")

SpringMVC向前端返回json格式的數據時,日期類型默認返回時間戳,那么我們可以通過此注解將時間返回為固定格式的字符串。
使用此注解需要引入一下jar包(需要特別注意的是jackson最新的版本對此功能不兼容,因此建議選擇2.6.1或者以下的版本):

[html]  view plain  copy
 
 print?
    1. <dependency>  
    2.     <groupId>org.codehaus.jackson</groupId>  
    3.     <artifactId>jackson-mapper-asl</artifactId>  
    4.     <version>1.9.13</version>  
    5. </dependency>  
    6. <dependency>  
    7.     <groupId>com.fasterxml.jackson.core</groupId>  
    8.     <artifactId>jackson-core</artifactId>  
    9.     <version>2.6.1</version>  
    10. </dependency>  
    11. <dependency>  
    12.     <groupId>com.fasterxml.jackson.core</groupId>  
    13.     <artifactId>jackson-databind</artifactId>  
    14.     <version>2.6.1</version>  
    15. </dependency>  

本文轉自http://blog.csdn.net/kylinah/article/details/53101068 感謝作者


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM