package com.atguigu.config; import com.atguigu.constant.LocalDateTimeConstant; import com.atguigu.interceptor.LoginAuthInterceptor; import com.atguigu.json.JacksonObjectMapper; import com.atguigu.properties.InterceptorsProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.text.SimpleDateFormat; import java.util.List; @Component @Slf4j public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Autowired private LoginAuthInterceptor loginAuthInterceptor; @Autowired private InterceptorsProperties interceptorsProperties; /** * * 解决跨域 * * @param registry 跨域注册表 */ protected void addCorsMappings(CorsRegistry registry) { log.info("开始跨域注册表..."); registry.addMapping("/**")// 添加路径规则 .allowCredentials(true)// 是否允许在跨域的情况下传递Cookie .allowedOriginPatterns("*")// 允许请求来源的域规则 .allowedMethods("*").allowedHeaders("*");// 允许所有的请求头 } /** * 注册自定义拦截器 * * @param registry InterceptorRegistry */ protected void addInterceptors(InterceptorRegistry registry) { log.info("开始注册自定义拦截器..."); // 需要拦截的 registry.addInterceptor(loginAuthInterceptor).addPathPatterns("/**") .excludePathPatterns(interceptorsProperties.getNoAuthUrls()); } /** * 扩展Spring MVC框架的消息转化器 * * @param converters 转换器 */ public void extendMessageConverters(List> converters) { log.info("扩展消息转换器..."); // 创建一个消息转换器对象 MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); // 需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据 converter.setObjectMapper(new JacksonObjectMapper()); // 添加条件判断,只应用于特定的请求路径 converter.getObjectMapper().setDateFormat(new SimpleDateFormat(LocalDateTimeConstant.DEFAULT_DATE_TIME_SECOND_FORMAT)); // 将自己的消息转化器加入容器中 converters.add(converter); } }