ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JAVA后端如何解决跨域问题

2021-11-25 18:33:36  阅读:22  来源: 互联网

标签:fastjson fastJsonHttpMessageConverter JAVA 跨域 后端 springframework SerializerFeatu


JAVA后端如何解决跨域问题

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @author 21029045
 * Created on 2021/11/25.
 */
@Configuration
@ServletComponentScan("xxxxxxxxx")
public class WebConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(3600);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(httpMessageConverter());
    }

    @Bean
    protected HttpMessageConverter<?> httpMessageConverter() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setFeatures(Feature.UseBigDecimal);
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteMapNullValue);

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.parseMediaType(ActuatorMediaType.V2_JSON), MediaType.parseMediaType(ActuatorMediaType.V1_JSON)));
        fastJsonHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);

        return fastJsonHttpMessageConverter;
    }

}

标签:fastjson,fastJsonHttpMessageConverter,JAVA,跨域,后端,springframework,SerializerFeatu
来源: https://blog.csdn.net/WUZHICAICHAN/article/details/121544228

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有