SpringMVC对日期类型的转换

  在作web开发的时候,页面传入的都是String类型,SpringMVC能够对一些基本的类型进行转换,可是对于日期类的转换可能就须要咱们配置。前端

  一、若是查询类使咱们本身写,那么在属性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd")  ,便可将String转换为Date类型,以下web

@DateTimeFormat(pattern = "yyyy-MM-dd")  
private Date createTime;  

  二、若是咱们只负责web层的开发,就须要在controller中加入数据绑定:spring

1 @InitBinder  
2 public void initBinder(WebDataBinder binder) {  
3 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
4 dateFormat.setLenient(false);  
5 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:容许输入空值,false:不能为空值 

  三、能够在系统中加入一个全局类型转换器json

  实现转换器mvc

 1 public class DateConverter implements Converter<String, Date> {    
 2 @Override    
 3 public Date convert(String source) {    
 4     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    
 5     dateFormat.setLenient(false);    
 6     try {    
 7         return dateFormat.parse(source);    
 8     } catch (ParseException e) {    
 9         e.printStackTrace();    
10     }           
11     return null;    
12 }    

  进行配置:app

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">    
        <property name="converters">    
            <list>    
                <bean class="com.doje.XXX.web.DateConverter" />    
            </list>    
        </property>    
</bean> 
<mvc:annotation-driven conversion-service="conversionService" />  

  四、若是将日期类型转换为String在页面上显示,须要配合一些前端的技巧进行处理。ide

  五、SpringMVC使用@ResponseBody返回json时,日期格式默认显示为时间戳。this

 1 @Component("customObjectMapper")  
 2 public class CustomObjectMapper extends ObjectMapper {  
 3   
 4     public CustomObjectMapper() {  
 5         CustomSerializerFactory factory = new CustomSerializerFactory();  
 6         factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {  
 7             @Override  
 8             public void serialize(Date value, JsonGenerator jsonGenerator,  
 9                     SerializerProvider provider) throws IOException, JsonProcessingException {  
10                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
11                 jsonGenerator.writeString(sdf.format(value));  
12             }  
13         });  
14         this.setSerializerFactory(factory);  
15     }  
16 }  

  配置以下:spa

<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>  

  六、date类型转换为json字符串时,返回的是long time值,若是须要返回指定的日期的类型的get方法上写上@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") ,便可将json返回的对象为指定的类型。code

@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;  
}  
相关文章
相关标签/搜索