SpringBoot中消息转化器的作用
在整个数据流转过程中,前端的请求报文转化为Java对象,Java对象转化为响应报文,这里就用到了HttpMessageConverter(消息转换器)。用以解决数据的格式问题或者数据精度丢失的问题。
实现
package com.wj.reggie_take_out.config;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.wj.reggie_take_out.interceptors.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.math.BigInteger;
import java.util.List;
/**
* @Description: 静态资源映射
* @Author WJ
* @Date 2023/4/16:10:51
* @Version V1.0
**/
@Slf4j
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
/**
* 静态资源路径映射
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
log.info("开始静态资源映射");
}
/**
* 拦截器
* @param registry
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//拦截所有请求
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/backend/page/login/login.html");
}
/**
* 消息转换器
* @param converters
*/
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("消息转换器");
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class,ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE,ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.registerModule(new JavaTimeModule());
messageConverter.setObjectMapper(objectMapper);
converters.add(0,messageConverter);
}
}