Spring MVC 创建自定义转换器

         我们在使用SpringMVC时,常常需要把表单中的参数映射到我们对象的属性中,我们可以在默认的spring-servlet.xml加上如下的配置即可做到普通数据类型的转换,如将String转换成Integer和Double等:

          <mvc:annotation-driven />

          或

          <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />

          其实  <mvc:annotation-driven /> 标签会默认创建并注册一个RequestMappingHandlerMapping(在Spring3.2之前是DefaultAnnotationHandlerMapping) 和 RequestMappingHandlerAdapter (Spring3.2之前是AnnotationMethodHandlerAdapter),当然,如果上下文有对应的显示实现类,将该注解注册的覆盖掉。该注解还会创建一个ConversionService,即FormattingConversionServiceFactoryBean。

         但如果你想将字符串映射成对象中的时间对象Date,Spring默认没有提供这种功能,需要你自己实现,即自定义转换器:

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 字符串到日期的转换器
 * @author manzhizhen
 *
 * 2015年6月4日
 */
public class StringToDateConverter implements Converter<String, Date>{
   
    public StringToDateConverter() {
        System.out.println("转换器我出生啦");
    }

    @Override
    public Date convert(String source) {
        if(StringUtils.isBlank(source)) {
            return null;
        }
       
        Date date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = format.parse(source.trim());
        } catch (Exception e) {
            try {
                format = new SimpleDateFormat("yyyyMMddHHmmss");
                date = format.parse(source.trim());
            } catch (Exception e1) {
                try {
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    date = format.parse(source.trim());
                } catch (Exception e2) {
                }
            }
        }
       
        return date;
    }
}

 测试用的数据对象如下:

package com.manzhizhen.beans;

import java.io.Serializable;
import java.util.Date;

/**
 * 传参对象
 * @author 易振强
 *
 * 2015年6月10日
 */
public class ParamObj implements Serializable {
	private static final long serialVersionUID = -7850639976682528281L;

	private Date date;
	private Double ratio;

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Double getRatio() {
		return ratio;
	}

	public void setRatio(Double ratio) {
		this.ratio = ratio;
	}
}

 控制器的测试代码如下:

package com.manzhizhen.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.manzhizhen.beans.ParamObj;

/**
 * 测试控制器
 * @author manzhizhen
 *
 * 2015年6月10日
 */
@Controller
@RequestMapping("/test")
public class TestController {

	@RequestMapping(value="/inputstr.htm", method=RequestMethod.POST)
	public ModelAndView deal(HttpServletRequest request, ParamObj paramObj) {
		ModelAndView mv = new ModelAndView();
		
		System.out.println(paramObj);
		
		mv.setViewName("/test/test.jsp");
		return mv;
	}
	
	@ExceptionHandler(Exception.class)
	public void ExceptionHandler(Exception e) {
		System.out.println(e);
	}
}

 测试页面index.jsp:

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8" language="java" %>
<html>
<head></head>
<body style="width:80%;margin:10 auto">     
    <form action="test/inputstr.htm" method="post" >
        <input type="text" value="2015-01-02" id="date" name="date"/>
        <input type="text" value="3.04" id="ratio" name="ratio"/>
        <input type="submit" value="submit" />
    </form>
</body>
</html>

准备好以上内容后,我们开始对SpringMVC的默认配置文件spring-servlet.xml进行配置了,加上如下内容:

    <bean id="myConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
         <property name="converters"> 
             <list> 
               <bean class="com.manzhizhen.converters.StringToDateConverter"/> 
            </list> 
        </property>
    </bean>
<mvc:annotation-driven conversion-service="myConversionService" />

注意,只能配置一个mvc:annotation-driven,谁先配置谁先生效,所以请去掉其他的  <mvc:annotation-driven />。

猜你喜欢

转载自manzhizhen.iteye.com/blog/2218996