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

    见上。

相关推荐
cfm_291417 分钟前
Leaf-segment号段模式
java
Wang's Blog19 分钟前
Java 项目实战: 交友项目 - 发布圈子动态:数据库表和接口文档介绍
java·数据库·交友
paopaokaka_luck20 分钟前
智慧电玩店管理系统(空闲机台随机分配、游玩时长概率模拟、积分自动结算、积分兑换闭环、 ECharts经营分析、 腾讯地图选址)
java·人工智能·mysql·echarts·推荐算法
LMT流氓兔41 分钟前
第五单元——第9课:防止同一次操作重复执行
java·服务器·数据库·算法·ai·langchain
OxYGC1 小时前
Spring 面经系列 · 第 6 篇:Spring MVC 请求全流程、父子容器与零配置原理
java·spring·mvc
code2cat1 小时前
Java高级篇之JDBC:连接数据库,完成查询、更新与事务
java·开发语言·数据库
bksczm1 小时前
Redis数据结构之string
java·redis·mybatis
cc_瀚海知行1 小时前
资料检索 1|直接放入全文、按需读文件和先检索,有什么区别?
java·人工智能·ai
BioRunYiXue1 小时前
使用docker分析高通量测序数据
java·数据库·人工智能·spring cloud·docker·tomcat·html
小尹哥-程序员1 小时前
第9集:Spring AI Advisor链:像Spring MVC拦截器一样优雅
人工智能·spring·mvc