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

    见上。

相关推荐
J_liaty21 分钟前
Spring Security整合JWT与Redis实现权限认证
java·redis·spring·spring-security
三角叶蕨29 分钟前
【苍穹外卖】day1
java
WAZYY061933 分钟前
通过LocalDateTime判断当前日期是否失效(附Java 中常用的 ISO 格式)
java·iso·日期·localdate·时间处理·日期处理·日期格式
超级种码37 分钟前
Redis:Redis键值淘汰策略
redis·spring·bootstrap
皙然39 分钟前
SpringBoot 自动装配深度解析:从底层原理到自定义 starter 实战(含源码断点调试)
java·spring boot·spring
NE_STOP42 分钟前
SpringBoot3-外部化配置与aop实现
java
ThinkPet1 小时前
【AI】大模型知识入门扫盲以及SpringAi快速入门
java·人工智能·ai·大模型·rag·springai·mcp
派大鑫wink1 小时前
【Day39】Spring 核心注解:@Component、@Autowired、@Configuration 等
java·后端·spring
输出输入1 小时前
JAVA能进行鸿蒙系统应用的开发吗
java
a努力。1 小时前
宇树Java面试被问:数据库死锁检测和自动回滚机制
java·数据库·elasticsearch·面试·职场和发展·rpc·jenkins