SpringMVC可以帮我们自动转换类型,
String->Integer
String->Double
String->Boolean
String->日期类型
2000/1/1写这种格式可以把字符串转换成日期,
2000-1-1这种就得需要自定义类型转换器了。
如果没有自定义类型转换器的话,Date date类型在表单中提交2000/1/1会自动转换,
但是2000-1-1就不能自动转换了。会出现HTTP Status 400-Bad Request
下面就介绍自定义类型转换器
之前讲过,MVC是基于组件的。我们需要注册一个类型转换器,当类型转化器注册成功之后,
前端控制器就会找类型转换器。
converter转换器
package cn.itcast.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
public class StringToDateConverter implements Converter<String,Date> {
@Override
public Date convert(String source) {
if (source ==null) {
throw new RuntimeException("请您传入数据");
}
//把字符串转换日期
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
//把字符串转换日期
return df.parse(source);
} catch (Exception e) {
throw new RuntimeException("数据类型转换出现错误");
}
}
} resources下的springmvc.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解扫描--> <context:component-scan base-package="cn.itcast"></context:component-scan> <!--视图解析器对象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置自定义类型转换器--> <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.itcast.utils.StringToDateConverter"/> </set> </property> </bean> <!--开启SpringMVC框架注解的支持--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/> </beans>

京公网安备 11010502036488号