ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
类型转换需要继承 `org.springframework.core.convert.converter.Converter.java`接口 一.编写自定义类型转换器 `StringToDateConverter.java`,代码如下 ~~~ package com.youge.utils; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-25 11:20 */ public class StringToDateConverter implements Converter<String, Date> { @Override public Date convert(String s) { if(s==null){ throw new RuntimeException("请传入数据!"); } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { return df.parse(s); } catch (Exception e) { throw new RuntimeException("数据类型转换出现错误"); } } } ~~~ ***** 二.在配置文件`springmvc.xml`配置自定义类型转换器 ~~~ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 开启注解扫描--> <context:component-scan base-package="com.youge"></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="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.youge.utils.StringToDateConverter"/> </set> </property> </bean> <!-- 开启SpringMVC框架注解的支持--> <mvc:annotation-driven conversion-service="conversionService" /> </beans> ~~~