当前位置: 首页 > news >正文

Spring MVC 对象转换器:初级开发者入门指南

Spring MVC 对象转换器:初级开发者入门指南

为什么需要对象转换器?
在 Web 应用中,我们经常需要处理不同类型的对象。例如:前端数据到后端对象 :用户通过表单提交的数据通常是HttpServletRequest 对象,我们需要将其转换为 Java 对象(如 POJO)以便进行业务处理。后端对象到前端展示 :在将数据返回给前端时,可能需要将 Java 对象转换为适合前端展示的格式(如 JSON 或 XML)。对象转换是一个常见且重要的任务。它允许我们将一种类型的对象转换为另一种类型,以便在不同的层(如控制器、服务和视图)之间进行数据传递和处理。本文将详细介绍 Spring MVC 中的对象转换器,帮助初级开发者理解和掌握这一关键概念。


一、使用 Converter 接口

Converter<S, T> 接口用于将类型 S 转换为类型 T,适用于简单类型或自定义对象转换。

1. 实现自定义 Converter
import org.springframework.core.convert.converter.Converter;// 示例:将字符串 "yyyy-MM-dd" 转换为 Date 对象
public class StringToDateConverter implements Converter<String, Date> {private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");@Overridepublic Date convert(String source) {try {return dateFormat.parse(source);} catch (ParseException e) {throw new IllegalArgumentException("无效的日期格式,请使用 yyyy-MM-dd");}}
}
2. 注册 Converter

通过 WebMvcConfigurer 配置类注册自定义转换器:

@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(new StringToDateConverter());}
}

二、使用 Formatter 接口

Formatter<T> 专门用于处理字符串与对象的转换(如 HTTP 请求参数的转换)。

1. 实现自定义 Formatter
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.util.Locale;public class DateFormatter implements Formatter<Date> {private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");@Overridepublic Date parse(String text, Locale locale) throws ParseException {return dateFormat.parse(text);}@Overridepublic String print(Date date, Locale locale) {return dateFormat.format(date);}
}
2. 注册 Formatter

同样通过 WebMvcConfigurer 注册:

@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addFormatter(new DateFormatter());}
}

三、使用 HttpMessageConverter(处理 JSON/XML)

当使用 @RequestBody@ResponseBody 时,Spring 使用 HttpMessageConverter 进行对象与 JSON/XML 的转换。常用的是 Jackson 的 MappingJackson2HttpMessageConverter

1. 自定义 Jackson 的 ObjectMapper
@Configuration
public class JacksonConfig {@Beanpublic ObjectMapper objectMapper() {ObjectMapper mapper = new ObjectMapper();mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);return mapper;}@Beanpublic MappingJackson2HttpMessageConverter jacksonConverter(ObjectMapper objectMapper) {return new MappingJackson2HttpMessageConverter(objectMapper);}
}
2. 注册自定义 HttpMessageConverter
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));}@Beanpublic ObjectMapper objectMapper() {// 同上}
}

四、使用 @InitBinder(局部绑定)

在控制器中为特定字段注册自定义编辑器。

示例:绑定日期格式
@Controller
public class MyController {@InitBinderpublic void initBinder(WebDataBinder binder) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));}
}

五、常见场景示例

1. 枚举类型转换

将请求参数转换为枚举:

public enum Status {ACTIVE, INACTIVE;
}// 自定义 Converter
public class StringToStatusConverter implements Converter<String, Status> {@Overridepublic Status convert(String source) {return Status.valueOf(source.toUpperCase());}
}
2. 自定义对象转换

String 转换为 User 对象:

public class StringToUserConverter implements Converter<String, User> {@Overridepublic User convert(String source) {String[] parts = source.split(",");User user = new User();user.setName(parts[0]);user.setAge(Integer.parseInt(parts[1]));return user;}
}

六、注意事项

  1. 优先级ConverterFormatter 的注册顺序可能影响结果。
  2. 全局 vs 局部@InitBinder 仅作用于当前控制器,而 Converter/Formatter 是全局的。
  3. JSON 配置:在 Spring Boot 中,可以通过 application.properties 配置 Jackson:
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=GMT+8
    

通过合理使用这些转换器,可以灵活处理 Spring MVC 中的数据类型转换需求。

http://www.lryc.cn/news/540647.html

相关文章:

  • 语音直播交友app出海:语音直播交友系统软件源码搭建国际化发展技术层面分析
  • Web Scraper,强大的浏览器爬虫插件!
  • EasyRTC:基于WebRTC与P2P技术,开启智能硬件音视频交互的全新时代
  • go 定时任务 gocron timer
  • uniapp引入uview组件库(可以引用多个组件)
  • MySQL主从架构
  • 科普mfc100.dll丢失怎么办?有没有简单的方法修复mfc100.dll文件
  • 论文笔记:How Much Can Time-related Features Enhance Time Series Forecasting?
  • Qt学习(六) 软件启动界面 ,注册表使用 ,QT绘图, 视图和窗口绘图,Graphics View绘图框架:简易CAD
  • JavaScript系列(80)--WebAssembly 基础入门
  • 蓝桥杯刷题2.21|笔记
  • 053 性能压测 单机锁 setnx
  • 【天线】IFA天线知识点摘抄
  • Mysql视图有什么作用?你是否使用过视图?
  • 【vue项目如何利用event-stream实现文字流式输出效果】
  • 微信问题总结(onpageshow ,popstate事件)
  • 【Gin-Web】Bluebell社区项目梳理3:社区相关接口开发
  • Unity 聊天气泡根据文本内容适配
  • 对学习编程语言的一些理解
  • MySQL MHA 部署全攻略:从零搭建高可用数据库架构
  • windows怎样查看系统信息(处理器等)
  • 007 HBuilderX提示IDE service port disabled. To use CLI Call, open IDE
  • 计算机网络之TCP的可靠传输
  • Python爬虫系列教程之第十四篇:爬虫项目部署、调度与监控系统
  • 线程与进程的深入解析及 Linux 线程编程
  • 在ubuntu上用Python的openpyxl模块操作Excel的案例
  • 【OS安装与使用】part6-ubuntu 22.04+CUDA 12.4运行MARL算法(多智能体强化学习)
  • 【Python爬虫(35)】解锁Python多进程爬虫:高效数据抓取秘籍
  • HarmonyOS 开发套件 介绍 ——上篇
  • Linux 高级篇 日志管理、定制自己的Linux系统、备份与恢复