一. Web相关

1. JS不兼容Java Long类型数据, 需要进行格式转换, 将Long自动转换为文本

// 创建配置类并继承WebMvcConfigurationSupport类, 重写configureMessageConverters方法(需要放入容器)
/**
 * 消息转换器配置: 配置Long转换为String
 * @param converters
 */
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    log.info("配置Jackson转换器");
    ObjectMapper objectMapper = new ObjectMapper();
    //序列化的时候序列对象的所有非空属性
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //反序列化时候遇到不匹配的属性并不抛出异常
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //序列化时候遇到空对象不抛出异常
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    //反序列化的时候如果是无效子类型,不抛出异常
    objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
    //不使用默认的dateTime进行序列化,
    objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
    //自定义的序列化类
    SimpleModule module = new SimpleModule();
    module.addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE);
    module.addSerializer(Long.TYPE, ToStringSerializer.instance);
    module.addSerializer(Long.class, ToStringSerializer.instance);
    //使用JSR310提供的序列化类,里面包含了大量的JDK8时间序列化类
    objectMapper.registerModules(new JavaTimeModule(), module);
    jackson2HttpMessageConverter.setObjectMapper(objectMapper);
    // 此处需要加上0, 将自定义消息转换器放在最前面
    converters.add(0, jackson2HttpMessageConverter);
}

2. 跨域配置

  • 方法1: 通过继承WebMvcConfigurationSupport类并重写addCorsMappings方法(需要放入容器)
    此方法在项目中使用了自定义拦截器后会失效, 建议使用方法2

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("/**")
              .allowedOrigins(new String[]{"*"})
              .allowedOriginPatterns(new String[]{"*"})
              .allowCredentials(true)
              .allowedMethods(new String[]{"GET", "POST", "DELETE", "PUT"})
              .allowedHeaders(new String[]{"*"})
              .maxAge(3600L);
    }
  • 方法2: 往容器中注入CorsFilter对象

    
    @Bean
    public CorsFilter corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration corsConfiguration = new CorsConfiguration();
      corsConfiguration.addAllowedOriginPattern("*");
      corsConfiguration.addAllowedHeader("*");
      corsConfiguration.addAllowedMethod("POST, GET, OPTIONS, DELETE, PUT");
      corsConfiguration.addExposedHeader("Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
      corsConfiguration.setMaxAge(3600L);
      source.registerCorsConfiguration("/**", corsConfiguration);
      return new CorsFilter(source);
    }
    

发表评论