SpringMVC的消息转换器

[复制链接]
发表于 2025-11-15 01:31:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
       SpringMVC的消息转换器(Message Converter)是Spring框架中用于处置处罚HTTP哀求和相应体与Java对象之间转换的组件。它们使得开辟职员可以轻松地将HTTP哀求的数据映射到方法参数,并将返回的对象转换为HTTP相应。
工作原理

       当一个HTTP哀求到达Spring MVC应用步调时,框架会根据哀求的内容范例(Content-Type)和继承范例(Accept)来选择符合的消息转换器。比方,假如客户端发送了一个JSON格式的POST哀求,那么Spring MVC会选择MappingJackson2HttpMessageConverter来将哀求体反序列化为Java对象。同样地,当方法返回一个Java对象并须要将其发送给客户端时,Spring MVC会利用相应的消息转换器来序列化这个对象。
常见的内置转换器

       在SpringMVC中,消息转换器通常通过HttpMessageConverter接口实现。Spring MVC提供了多种内置的消息转换器来支持差异的媒体范例,比方JSON、XML等。以下是几个常见的内置转换器:

  • MappingJackson2HttpMessageConverter:用于支持JSON格式的HTTP消息,依赖于Jackson库。
  • MappingJackson2XmlHttpMessageConverter:用于支持XML格式的HTTP消息,同样依赖于Jackson库。
  • StringHttpMessageConverter:用于处置处罚纯文本字符串的HTTP消息。
  • FormHttpMessageConverter:用于处置处罚表单数据(application/x-www-form-urlencoded或multipart/form-data),包罗尺度表单和文件上传。
  • ByteArrayHttpMessageConverter:用于处置处罚二进制数据,好比图片或文件下载。
  • Jaxb2RootElementHttpMessageConverter:基于JAXB API,用于XML数据的序列化和反序列化。
  • SourceHttpMessageConverter:用于处置处罚基于javax.xml.transform.Source的XML消息。
  • ResourceHttpMessageConverter:用于处置处罚资源文件,如文件下载
设置消息转换器

     你可以通过以下几种方式设置消息转换器:

  •         通过Java设置类
                     假如你正在利用基于Java的设置,可以通过实现WebMvcConfigurer接口并重写configureMessageConverters方法来添加自界说的消息转换器:
    1. @Configuration
    2. public class WebConfig implements WebMvcConfigurer {
    3.     @Override
    4.     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    5.         // 添加默认的消息转换器
    6.         WebMvcConfigurer.super.configureMessageConverters(converters);
    7.         // 添加自定义的消息转换器
    8.         converters.add(new CustomHttpMessageConverter());
    9.     }
    10. }
    复制代码
  •         通过Spring XML设置
                     假如你还在利用XML设置,则可以在设置文件中界说<mvc:message-converters>元素:
    1. <mvc:annotation-driven>
    2.     <mvc:message-converters register-defaults="true">
    3.         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    4.         <!-- 其他自定义的消息转换器 -->
    5.     </mvc:message-converters>
    6. </mvc:annotation-driven>
    复制代码
  •         主动设置(Spring Boot)
                     在Spring Boot中,框架会根据类路径上的库主动设置符合的消息转换器。比方,假如Jackson库在类路径上,Spring Boot会主动注册MappingJackson2HttpMessageConverter。
自界说消息转换器

       为了创建自界说的消息转换器,你须要实现HttpMessageConverter<T>接口,此中T是你想要转换的对象范例。这个接口有三个告急的方法须要实现:

  • boolean canRead(Class<?> clazz, MediaType mediaType):判定是否可以或许读取指定范例的对象。
  • boolean canWrite(Class<?> clazz, MediaType mediaType):判定是否可以或许写入指定范例的对象。
  • List<MediaType> getSupportedMediaTypes():返回支持的媒体范例列表。
  • T read(Class<? extends T> clazz, HttpInputMessage inputMessage):从HTTP输入消息中读取并转换为对象。
  • void write(T t, MediaType contentType, HttpOutputMessage outputMessage):将对象转换为HTTP输出消息。
        一旦实现了上述接口,就可以将其添加到SpringMVC的设置中,以便框架知道在处置处罚特定范例的HTTP消息时利用哪个转换器。除了实现HttpMessageConverter<T>接口外,你还可以通过设置类或XML文件控制哪些转换器被利用,以及它们的优先级序次。这对于确保精确处置处罚差异范例的消息非常告急。
自界说消息转换器实例

1. 创建业务对象

    起首,我们须要一个Java类来表现我们要序列化和反序列化的数据模子。这里我们创建一个简单的CustomObject:
  1. public class CustomObject {
  2.     private Long id;
  3.     private String name;
  4.     // Getters and Setters
  5.     public Long getId() {
  6.         return id;
  7.     }
  8.     public void setId(Long id) {
  9.         this.id = id;
  10.     }
  11.     public String getName() {
  12.         return name;
  13.     }
  14.     public void setName(String name) {
  15.         this.name = name;
  16.     }
  17.     @Override
  18.     public String toString() {
  19.         return "CustomObject{" +
  20.                 "id=" + id +
  21.                 ", name='" + name + '\'' +
  22.                 '}';
  23.     }
  24. }
复制代码
2. 实现自界说消息转换器

     接下来,我们将创建一个自界说的消息转换器,用于处置处罚特定媒体范例的数据。假设我们的自界说媒体范例是application/vnd.example.v1+json。
  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import org.springframework.http.HttpInputMessage;
  3. import org.springframework.http.HttpOutputMessage;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.http.converter.AbstractHttpMessageConverter;
  6. import org.springframework.http.converter.HttpMessageNotReadableException;
  7. import org.springframework.http.converter.HttpMessageNotWritableException;
  8. import java.io.IOException;
  9. import java.util.Collections;
  10. public class CustomJsonHttpMessageConverter extends AbstractHttpMessageConverter<CustomObject> {
  11.     private final ObjectMapper objectMapper = new ObjectMapper();
  12.     public CustomJsonHttpMessageConverter() {
  13.         // 支持的媒体类型
  14.         super(new MediaType("application", "vnd.example.v1+json"));
  15.     }
  16.     @Override
  17.     protected boolean supports(Class<?> clazz) {
  18.         // 指定转换器支持的类型
  19.         return CustomObject.class.isAssignableFrom(clazz);
  20.     }
  21.     @Override
  22.     protected CustomObject readInternal(Class<? extends CustomObject> clazz, HttpInputMessage inputMessage)
  23.             throws IOException, HttpMessageNotReadableException {
  24.         // 读取并反序列化为CustomObject
  25.         return objectMapper.readValue(inputMessage.getBody(), clazz);
  26.     }
  27.     @Override
  28.     protected void writeInternal(CustomObject object, HttpOutputMessage outputMessage)
  29.             throws IOException, HttpMessageNotWritableException {
  30.         // 序列化CustomObject到输出流中
  31.         objectMapper.writeValue(outputMessage.getBody(), object);
  32.     }
  33. }
复制代码
3. 设置消息转换器

     为了使Spring MVC知道利用我们自界说的消息转换器,我们须要在设置类中注册它。下面是怎样在基于Java的设置中做到这一点:
  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.http.converter.HttpMessageConverter;
  3. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  4. import java.util.List;
  5. @Configuration
  6. public class WebConfig implements WebMvcConfigurer {
  7.     @Override
  8.     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  9.         // 添加自定义的消息转换器
  10.         converters.add(new CustomJsonHttpMessageConverter());
  11.         // 如果需要保留默认的消息转换器,可以这样添加
  12.         // WebMvcConfigurer.super.configureMessageConverters(converters);
  13.     }
  14. }
复制代码
4. 控制器层

     如今,我们可以创建一个控制器来利用这个自界说的消息转换器:
  1. import org.springframework.http.MediaType;
  2. import org.springframework.web.bind.annotation.*;
  3. @RestController
  4. @RequestMapping("/custom")
  5. public class CustomController {
  6.     @PostMapping(consumes = "application/vnd.example.v1+json", produces = "application/vnd.example.v1+json")
  7.     public CustomObject createCustomObject(@RequestBody CustomObject customObject) {
  8.         // 处理业务逻辑...
  9.         System.out.println("Received: " + customObject);
  10.         return customObject; // 返回相同的对象作为响应
  11.     }
  12.     @GetMapping(value = "/{id}", produces = "application/vnd.example.v1+json")
  13.     public CustomObject getCustomObject(@PathVariable Long id) {
  14.         // 模拟查询操作
  15.         CustomObject obj = new CustomObject();
  16.         obj.setId(id);
  17.         obj.setName("Example Object " + id);
  18.         return obj;
  19.     }
  20. }
复制代码
5. 非常处置处罚

     当消息转换过程中发生错误时,Spring MVC会抛出HttpMessageNotReadableException或HttpMessageNotWritableException。你可以通过全局非常处置处罚器来捕捉这些非常并返回友爱的错误信息给客户端。
  1. import org.springframework.http.HttpStatus;
  2. import org.springframework.http.ResponseEntity;
  3. import org.springframework.http.converter.HttpMessageNotReadableException;
  4. import org.springframework.http.converter.HttpMessageNotWritableException;
  5. import org.springframework.web.bind.annotation.ControllerAdvice;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. @ControllerAdvice
  8. public class GlobalExceptionHandler {
  9.     @ExceptionHandler(HttpMessageNotReadableException.class)
  10.     public ResponseEntity<String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
  11.         return new ResponseEntity<>("Error reading message: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
  12.     }
  13.     @ExceptionHandler(HttpMessageNotWritableException.class)
  14.     public ResponseEntity<String> handleHttpMessageNotWritable(HttpMessageNotWritableException ex) {
  15.         return new ResponseEntity<>("Error writing message: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  16.     }
  17. }
复制代码
6. 全局设置与性能优化

     假如你有多个自界说转换器大概想要对全部转换器举行一些全局设置(好比设置日期格式),你可以在设置类中做进一步的调解。别的,对于高流量的应用步调,思量利用缓存或异步处置处罚以进步性能。
比方,你可以设置Jackson的ObjectMapper以更好地控制JSON的序列化和反序列化举动:
  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class JacksonConfig {
  7.     @Bean
  8.     public ObjectMapper objectMapper() {
  9.         ObjectMapper mapper = new ObjectMapper();
  10.         mapper.registerModule(new JavaTimeModule()); // 支持Java 8时间API
  11.         // 这里还可以设置其他全局配置选项
  12.         return mapper;
  13.     }
  14. }
复制代码
然后,在你的自界说消息转换器中注入这个ObjectMapper bean:
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. public class CustomJsonHttpMessageConverter extends AbstractHttpMessageConverter<CustomObject> {
  3.     private final ObjectMapper objectMapper;
  4.     @Autowired
  5.     public CustomJsonHttpMessageConverter(ObjectMapper objectMapper) {
  6.         super(new MediaType("application", "vnd.example.v1+json"));
  7.         this.objectMapper = objectMapper;
  8.     }
  9.     // ... 省略其他方法 ...
  10. }
复制代码
    这将确保全部的CustomJsonHttpMessageConverter实例都利用同一个设置过的ObjectMapper,从而简化了设置而且进步了代码的划一性。
7. 设置与自界说

     利用@ConfigurationProperties举行设置

     对于复杂的设置需求,可以利用@ConfigurationProperties来创建一个设置类,从而将设置属性外部化。比方,假如你想要为Jackson ObjectMapper设置多个属性,你可以如许做:
  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class JacksonConfig {
  7.     @Bean
  8.     @ConfigurationProperties(prefix = "spring.jackson")
  9.     public ObjectMapper objectMapper() {
  10.         return new ObjectMapper();
  11.     }
  12. }
复制代码
在application.properties或application.yml中添加相应的设置项:
  1. spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
  2. spring.jackson.time-zone=UTC
  3. # 更多配置...
复制代码
自界说序列化器和反序列化器

      偶然默认的举动大概不符合业务需求,这时可以通过实现自界说的序列化器和反序列化器来调解数据处置处罚方式。以日期格式为例,假如想要同一处置处罚Java 8的时间范例,可以注册JavaTimeModule模块:
  1. @Bean
  2. public Module javaTimeModule() {
  3.     return new JavaTimeModule();
  4. }
复制代码
还可以通过继承JsonSerializer和JsonDeserializer来创建更加定制化的逻辑。
8. 性能优化

     缓存ObjectMapper

     确保ObjectMapper实例是单例且线程安全的,由于它不是线程安全的。通常情况下,Spring会为你管理这一点,但假如你手动创建了ObjectMapper,则须要特殊注意。
     异步处置处罚

     为了进步相应速率,尤其是在处置处罚大文件或复杂对象时,可以思量利用异步的消息转换。Spring MVC支持异步哀求处置处罚,允许你在配景线程池中实行耗时使命而不壅闭主线程。
  1. @GetMapping("/async/{id}")
  2. public CompletableFuture<CustomObject> getCustomObjectAsync(@PathVariable Long id) {
  3.     return CompletableFuture.supplyAsync(() -> {
  4.         // 模拟耗时操作
  5.         try { Thread.sleep(1000); } catch (InterruptedException e) {}
  6.         CustomObject obj = new CustomObject();
  7.         obj.setId(id);
  8.         obj.setName("Async Example Object " + id);
  9.         return obj;
  10.     });
  11. }
复制代码
9. 安全性思量

     内容协商(Content Negotiation)

      确保你的应用步调精确地实现了内容协商机制,以防止攻击者利用不渴望的内容范例发起攻击。可以通过设置白名单来限定允许的内容范例,并确保全部转换器都只处置处罚颠末验证的媒体范例。
  1. @Override
  2. public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
  3.     configurer.favorPathExtension(false)
  4.               .favorParameter(true)
  5.               .parameterName("mediaType")
  6.               .ignoreAcceptHeader(true)
  7.               .useRegisteredExtensionsOnly(true)
  8.               .defaultContentType(MediaType.APPLICATION_JSON)
  9.               .mediaType("json", MediaType.APPLICATION_JSON)
  10.               .mediaType("xml", MediaType.APPLICATION_XML);
  11. }
复制代码
     数据验证

     始终对输入的数据举行验证,纵然是在序列化和反序列化之后。这可以资助防止诸如注入攻击等安全标题。
10. Spring Boot集成

       在Spring Boot中,很多设置已经被简化并主动化。你只须要确保所需的库(如Jackson)存在于类路径上,框架就会主动设置符合的消息转换器。别的,Spring Boot还提供了额外的功能,好比主动发现和注册转换器。
  1. # application.yml
  2. spring:
  3.   jackson:
  4.     serialization:
  5.       write-dates-as-timestamps: false
  6.     deserialization:
  7.       fail-on-unknown-properties: false
复制代码
11. 日志日志记录

       启用详细的日志日志记录有助于调试和监控监控消息转换过程中的任何标题。可以在application.properties中设置日志日志级别:
  1. logging.level.org.springframework.web=DEBUG
  2. logging.level.com.fasterxml.jackson=DEBUG
复制代码
12. 测试

       编写单元测试和集成测试来验证消息转换器的举动是否符合预期非常告急。JUnit和MockMvc可以资助你模拟HTTP哀求并查抄转换结果。
  1. @WebMvcTest
  2. class CustomControllerTest {
  3.     @Autowired
  4.     private MockMvc mockMvc;
  5.     @Test
  6.     void shouldReturnDefaultMessage() throws Exception {
  7.         mockMvc.perform(get("/custom/1").accept(MediaType.parseMediaType("application/vnd.example.v1+json")))
  8.               .andExpect(status().isOk())
  9.               .andExpect(content().contentType("application/vnd.example.v1+json"))
  10.               .andExpect(jsonPath("$.name").value("Example Object 1"));
  11.     }
  12. }
复制代码
利用注解控制消息转换

      在控制器层,你可以利用一些注解来控制消息转换的举动,好比@RequestBody和@ResponseBody:

  • @RequestBody:用于将HTTP哀求体的内容映射到方法参数,并利用恰当的HttpMessageConverter举行反序列化。
  • @ResponseBody:用于指示方法的返回值应该被直接写入HTTP相应体,而不是剖析为视图。
别的,另有@RestController注解,它是一个组合注解,等价于同时利用@Controller和@ResponseBody,简化了RESTful服务的开辟。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表