SpringMVC 自定义类型转换器
我们在使用SpringMVC时,常常需要把表单中的参数映射到我们对象的属性中,我们可以在默认的spring-servlet.xml加上如下的配置即可做到普通数据类型的转换,以字符串转日期为例:
定义一个类实现Converter接口(DateConverter.java),该接口有两个泛型:
package com.smbms.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
private String datePatter;
public void setDatePatter(String datePatter) {
this.datePatter = datePatter;
}
public Date convert(String s) {
Date date = null;
try {
date = new SimpleDateFormat(datePatter).parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
springmvc.xml配置文件:
<!--自定义类型转换器-->
<bean name="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.smbms.converter.DateConverter" p:datePatter="yyyy-MM-dd" />
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
web.xml:
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
咦,就这么点的吗?!