SpringMVC中自定义类型转换器

日期格式转换

新建CustomDateConverter.class

格式转换中

  • converter:可以将任意格式转换为任意格式
  • format:将String转换成任意格式
//java.text包
public class CustomDateConverter implements Converter<String,Date>{
     
   public CustomDateConverter(){
     
      System.out.println("实例化CustomDateConverter");
   }

   public Date convert(String source) {
     
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      try {
     
         return sdf.parse(source);
      } catch (ParseException e) {
           
         e.printStackTrace();
      }
      return null;
   }

}
  • Springmvc-servlet.xml中在mvc:annotation-driven标签里使用conversion-service属性引用我们自定义的参数转换器
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.chixing.util.CustomDateConverter"/>
        list>
    property>
bean>

在spring 中定义了3中类型转换接口,分别为:

  1. Converter接口 :使用最简单,最不灵活;

  2. ConverterFactory接口 :使用较复杂,比较灵活;

  3. GenericConverter接口 :使用最复杂,也最灵活;

示例1:

基本功能说明:

  1. 前台传递的数据格式形如:“zhangSan:888”;
http://localhost:8080/SpringMVCTest/test/conversionTest.action?person=zhangsan:888
class Person{
     
	String username;
	String password;
}

具体实现:

  1. 定义转换类,实现Converter接口;
  2. 装配自定义的conversionService;
public class StringToPersonConverter implements Converter<String,Person>{
     
	public Person convert(String source) {
     
		Person p1 = new Person();
		if(source != null){
     
			String[] items = source.split(":");
			p1.setUsername(items[0]);
			p1.setPasswd(items[1]);
		}
		return p1;
	}
}
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
		class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<list>
				<bean class="com.chixing.convertor.StringToPersonConverter" />
			list>
		property>
bean>

Controller

public String conversionTest(@RquestParam ("person") Person p,ModelMap modelMap){
     
	modelMap.put("person",p);
    return "test";
}

当前台发送请求:

将person=zhangsan:888传递到后台,被StringToPersonConverter转换为Person对象;

跳转到界面:test.jsp


	用户名:${person.username},
    密码:${person.password}

你可能感兴趣的:(Spring,springMvc)