spring mvc 类型转换

   讲解一下类型转换,例如在jsp页面,有一个日期类型的,jsp页面的日期类型都是String类型的,但是我后台的controller接收的是Date类型的,此时需要进行转换,如果不转换,页面会报一个400的错误。

  那么就说一下解决方案

  方案1:在你需要进行类型转换的controller加上下面的代码,不推荐使用,这种方式相比较比较冗余和复用,如果还有别的controller,我需要再次复制下面的代码,不是特别推荐使用

        @InitBinder
        public void initBinder(WebDataBinder binder) throws Exception {
            // Date.class必须是与controler方法形参pojo属性一致的date类型,这里是java.util.Date
            binder.registerCustomEditor(Date.class, new CustomDateEditor(
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        }

  方案2:创建Converter接口,实现Converter接口

   

public class CustomDateConverter implements Converter<String, Date>{

	public Date convert(String source) {
		Date date = null;
		try {
			System.out.println(source);
			date =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("hahahahahahahaaha");
		
		}
		return date;
	}
}

       

public class StringTirmConverter implements Converter<String, String>{

	public String convert(String source) {
		try {
			if(source!=null){
				source = source.trim();
				if(source.equals("")){
					return null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return source;
	}

	
}

   

	<!-- 注解适配器 -->
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
	<!-- 	在webBindingInitializer中注入自定义属性编辑器、自定义转换器 -->
		<property name="webBindingInitializer" ref="customBinder"></property>
	</bean>

	<!-- 配置视图解析器 要求将jstl的包加到classpath -->
	<!-- ViewResolver -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	
	<!-- 	自定义webBinder  -->
	<bean id="customBinder"
		class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
		<!-- 使用converter进行参数转 -->
		<property name="conversionService" ref="conversionService" />
	</bean>
	 
	 <!-- 转换器 -->
    <bean id="conversionService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<list>
				<bean class="com.dafei.ssm.controller.converter.CustomDateConverter"/>
				<bean class="com.dafei.ssm.controller.converter.StringTirmConverter"/>
			</list>
		</property>
	</bean> 

    还有另一种配置方式就是

	<mvc:annotation-driven conversion-service="conversionService"/>
	<bean id="conversionService"
		class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<list>
				<bean class="com.dafei.ssm.controller.converter.CustomDateConverter" />
				<bean class="com.dafei.ssm.controller.converter.StringTirmConverter"/>
			</list>
		</property>
	</bean>

    

猜你喜欢

转载自1193355343.iteye.com/blog/2367374