SpringMvc自定义类型转换器步骤

自定义类型转换器步骤:


	1.实现Converter接口
	
		/**
		 * 把XXXX-XX-XX字符串转成日期格式
		 */
		public class StringToDateConverter implements Converter<String,Date>{
     

			/**
			 * String source    传入进来字符串
			 * @param source
			 * @return
			 */
			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("数据类型转换出现错误");
				}
			}

		}
	
	2.在SpringMVC的配置文件中配置自定义转换器

	
		<?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">
			<!-- 配置spring创建容器时要扫描的包 -->
			<context:component-scan base-package="com.b3a4a.springmvc"></context:component-scan>
			<!-- 配置视图解析器 -->
			<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
				<!-- 默认访问/WEB-INF/pages/XXX.jsp -->
				<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.b3a4a.springmvc.converter.StringToDateConverter"/>
					</set>
				</property>
			</bean>
			<!-- 开启SpringMVC框架注解的支持 -->
			<mvc:annotation-driven conversion-service="conversionService"/>
			<!-- ********************** -->
		</beans>

SpringMvc自定义类型转换器步骤_第1张图片

你可能感兴趣的:(spring全家桶,springMvc)