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

    见上。

相关推荐
qq_185198699 小时前
(Spring Bean + delegateExpression)实现http服务 的完整可运行项目
spring
小Ti客栈9 小时前
Spring Boot 集成 Springdoc-OpenAPI 与 Knife4j实现接口文档与可视化调试
java·spring boot·后端
Ai拆代码的曹操10 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
动恰客流统计10 小时前
ReID边缘计算视觉统计:餐饮店客流增长的数字化破局路径
java·大数据·运维·人工智能
Ivanqhz11 小时前
Rust &‘static str浅析
java·前端·javascript·rust
weixin_4196583114 小时前
Docker 搭建 Jenkins 服务
java·docker·jenkins
captain37614 小时前
多线程线程安全问题
java·java-ee
CoderYanger14 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
灵极海15 小时前
LangChain4j RAG 实战完整指南:从入门到踩坑
java·langchain
yaoxin52112315 小时前
476. Java 反射 - 调用方法
java·开发语言