JAVA springmvc 转换器

时间:2021-10-18 19:30:27

一、有时候springmvc给咱们提供的数据转换并不能转换所有类型比如说由字符串类型转换Date类型,这时候需要我们自定义转换器,帮助springmvc转换我们需要的类型。

二、1)定义我们的转换器:

 package jd.com.contronller.jd.com.convert;

 import org.springframework.core.convert.converter.Converter;

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class CustomStringToDate implements Converter<String,Date> {
@Override
public Date convert(String s) {
try {
Date date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}

2)在springmvc配置文件添加我们的转换器:

         <!--自定义转换器 注意在注解驱动里指明引用-->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="jd.com.contronller.jd.com.convert.CustomStringToDate"/>
</set>
</property>
</bean>

3)需要注意:在注解驱动的添加我们的转换器id

 <mvc:annotation-driven conversion-service="conversionService"  />

因为转换器是处理器适配器进行处理的,如果我们不采用注解的方式,传统的引用如下:

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 扫描带Controller注解的类 -->
<context:component-scanbase-package="cn.itcast.springmvc.controller"/> <!-- 转换器配置 -->
<beanid="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<propertyname="converters">
<set>
<beanclass="jd.com.contronller.jd.com.convert.CustomStringToDate"/>
</set>
</property>
</bean>
<!-- 自定义webBinder -->
<beanid="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<propertyname="conversionService"ref="conversionService"/>
</bean>
<!--注解适配器 -->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<propertyname="webBindingInitializer"ref="customBinder"></property>
</bean>
<!-- 注解处理器映射器 -->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

注意的:

前端页面想显示日期格式需要定义下面标签:

  <td><fmt:formatDate value="${n.create_time}" pattern="yyyy-MM-dd HH:mm:ss" /> </td>

 需要注意格式需要和后面转换器类的格式一致,否则报错!!!!