SpringMVC 中实现自定义转换

自定义类型转换

SpringMVC 中实现自定义的参数类型转换有两种途径:

  • 实现 Converter 接口

  • 实现 Formatter 接口

1. 使用 Converter 接口

通过 Convert 接口来实现自定义转换及参数绑定,需要为 Spring 提供一个实现了 Converter 接口的类,并在 Spring MVC 中进行注册。

java 复制代码
import org.springframework.core.convert.converter.Converter;

public class DateConverter implements Converter<String, Date> {
    ...
}
  • 配置文件版:spring-web.xml

    xml 复制代码
    <mvc:annotation-driven conversion-service="conversionService"/>
    
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
      <property name="converters">
        <set>
          <bean class="com.demo1.converter.MyConverter"/>
        </set>
      </property>
    </bean>
  • 代码配置版:SpringWebConfig.java

    java 复制代码
    @Override
    public void addFormatters(FormatterRegistry registry) {
          registry.addConverter(new MyDateConverter());
      //  registry.addFormatter(new MyDateFormatter());
      }
  • Converter 接口的核心内容:

    java 复制代码
    @Override
    public Date convert(String str) {
    
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
      Date date = null;
      try {
        date = simpleDateFormat.parse(str);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    
      return date;
    }

2. 使用 Formatter 接口

了解

Formatter 接口的使用于 Converter 接口类似。

java 复制代码
public DateFormatter(String datePattern) {
  dateFormat = new SimpleDateFormat("MM-dd-yyyy");
}

@Override
public String print(Date object, Locale locale) {
  return dateFormat.format(object);
}

@Override
public Date parse(String text, Locale locale) throws ParseException {
  return dateFormat.parse(text);
}
  • 配置文件版:spring-web.xml

    xml 复制代码
    <mvc:annotation-driven conversion-service="conversionService"/>
    
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
      <property name="formatters">
        <set>
          <bean class="com.demo.web.support.DateFormatter"/>
        </set>
      </property>
    </bean>
  • 代码配置版:SpringWebConfig.java

    见上。

相关推荐
24k小善44 分钟前
Flink TaskManager详解
java·大数据·flink·云计算
想不明白的过度思考者1 小时前
Java从入门到“放弃”(精通)之旅——JavaSE终篇(异常)
java·开发语言
.生产的驴1 小时前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV1 小时前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
晨集1 小时前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城1 小时前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
椰羊~王小美2 小时前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
凯酱2 小时前
MyBatis-Plus分页插件的使用
java·tomcat·mybatis
程序员总部2 小时前
如何在IDEA中高效使用Test注解进行单元测试?
java·单元测试·intellij-idea
oioihoii2 小时前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23