springmvc配置日期转化

来源:互联网 发布:中国人均gdp近十年数据 编辑:程序博客网 时间:2024/05/15 00:25

我们在SpringMVC开发中,可能遇到比较多的问题就是前台与后台实体类之间日期转换处理的问题了,说问题也不大,但很多人开发中经常会遇到这个问题,有时很令人头疼,有时间问题暴露的不是很明显,然后逐渐对问题进行跟踪,会发现是日期类型转换失败“映射”不到对应的持久类的日期属性上造成的,由此我还特意写过一篇博文:SpringMVC中出现" 400 Bad Request "错误(用@ResponseBody处理ajax传过来的json数据转成bean)的解决方法。感兴趣的码农可以看一看,总结了常见造成springMVC出现“400 Bad Request”错误的七大原因,其中就有前台的字符串日期类型与后台的java日期类型匹配不上造成的。

       今天晚上呢,特意抽出宝贵的时间来总结归纳出一下解决这个问题的三大方法,分享给大家,以帮助更多像我一样的人。鄙人不才,如果过程中有讲解的不清或者不对的地方,还望认真阅读的您,留下你的宝贵意见或建议,以便您,我,还有大家更快更好的共同进步!

       好了,我们切入正题吧!

 

方法一:实体类中加日期格式化注解

[java] view plain copy
  1. @DateTimeFormat(pattern = "yyyy-MM-dd")  
  2. private Date receiveAppTime;  

如上,在对应的属性上,加上指定日期格式的注解,本人亲自测试过,轻松解决问题!

 

方法二:控制器Action中加入一段数据绑定代码

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


方法三:实现一个全局日期类型转换器并进行配置

         此方法较为复杂,请详细查看本人的这篇博文:SpringMVC配置全局日期转换器,处理日期转换异常

 

附加方法四:适合页面把日期类型转换成字符串且JSP,Freemark页面

JSP模版引擎方法:

[java] view plain copy
  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>   
  2. <fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>  

Freemarker模版引擎方法:

[java] view plain copy
  1. <input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" />  

 

OK了,完了,希望以上方法能帮助正在阅读的您!

转载请注明—作者:Java我人生(陈磊兴)   原文出处:http://blog.csdn.net/chenleixing/article/details/44708533

最后,认真看过的网友们,大神们,如有感觉我这个程序猿有哪个地方说的不对或者不妥或者你有很好的议或者建议或点子方法,还望您大恩大德施舍n秒的时间留下你的宝贵文字(留言),以便你,我,还有广大的程序猿们更快地成长与进步.......



配置全局

spring3.0配置日期转换可以通过配置自定义实现WebBingingInitializer接口的一个日期转换类来实现,方法如下

转换类:

  1. public class DateConverter implements WebBindingInitializer {    
  2.     
  3.     public void initBinder(WebDataBinder binder, WebRequest request) {    
  4.           
  5.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");    
  6.         binder.registerCustomEditor(Date.classnew CustomDateEditor(df, false));    
  7.     }    

在spring-servlet.xml当中的进行注册:

  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    
  2.     <!-- 日期格式转换 -->    
  3.     <property name="webBindingInitializer">    
  4.         <bean class="DateConverter" />    
  5.     </property>    
  6. </bean>  

 

spring3.1.1的处理进行调整,所以按照3.0的写法在3.1.1里面是无效的,通过查找资料及测试,发现可行方法

原因:

annotation-driven缺省注册类的改变 

Spring 3.0.x中使用了annotation-driven后,缺省使用DefaultAnnotationHandlerMapping 来注册handler method和request的mapping关系。 AnnotationMethodHandlerAdapter来在实际调用handlermethod前对其参数进行处理。 

 

在spring mvc 3.1中,对应变更为 
DefaultAnnotationHandlerMapping -> RequestMappingHandlerMapping 
AnnotationMethodHandlerAdapter -> RequestMappingHandlerAdapter 
AnnotationMethodHandlerExceptionResolver -> ExceptionHandlerExceptionResolver 

以上都在使用了annotation-driven后自动注册。 
  而且对应分别提供了AbstractHandlerMethodMapping , AbstractHandlerMethodAdapter和 AbstractHandlerMethodExceptionResolver以便于让用户更方便的实现自定义的实现类。 

 

<mvc:annotation-driven/>相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean,配置一些messageconverter。即解决了@Controller注解的使用前提配置。

 

spring mvc <mvc:annotation-driven />会自动启动Spring MVC的注解功能,但实际它做了哪些工作呢?

 

Java代码  
  1. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">  
  2. <property name="order" value="1" />  
  3. </bean>  
  4. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  5. <property name="webBindingInitializer">  
  6.   <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">  
  7.    <property name="conversionService" ref="conversionService" />  
  8.    <property name="validator" ref="validator" />  
  9.   </bean>  
  10. </property>  
  11. </bean>  
  12. <bean id="conversionService" class="org.springframework.samples.petclinic.util.PetclinicConversionServiceFactory" />  
  13. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />   


从上面的配置可以看出,我的配置应该是被sping的配置覆盖了,<mvc:annotation-driven />配置中已经包含了webBindingInitializer的配置,看来使用<mvc:annotation-driven />后与原来的配置出现了重复,这种情况下不管<mvc:annotation-driven />放在上面还是放在下面都会出现问题。

 

解决方法:

使用conversion-service来注册自定义的converter 
DataBinder实现了PropertyEditorRegistry, TypeConverter这两个interface,而在spring mvc实际处理时,返回值都是return binder.convertIfNecessary(见HandlerMethodInvoker中的具体处理逻辑)。因此可以使用customer conversionService来实现自定义的类型转换。 

<mvc:annotation-driven />中配置可以看出,AnnotationMethodHandlerAdapter已经配置了webBindingInitializer,我们可以通过设置其属性conversionService来实现自定义类型转换。

 

Java代码  
  1. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">    
  2.         <property name="converters">    
  3.             <list>    
  4.                 <bean class="com.doje.XXX.web.DateConverter" />    
  5.             </list>    
  6.         </property>    
  7.     </bean>  

 

 需要修改spring service context xml配置文件中的annotation-driven,增加属性conversion-service指向新增的conversionService bean。 

 

Java代码  
  1. <mvc:annotation-driven conversion-service="conversionService" />   

 

 实际自定义的converter如下。 

Java代码  
  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;    

0 0
原创粉丝点击