Spring MVC中解决跨域问题

根包下config包下创建SpringMvcConfiguration类,实现WebMvcConfigururer接口,重写其中的方法,以解决跨域问题:


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 允许跨域访问的路径
                .allowedOriginPatterns("*") // 允许跨域访问的域名
                .allowedMethods("*")   // 允许跨域访问的方法
                .allowedHeaders("*")   // 允许跨域访问的请求头
                .allowCredentials(true)   // 是否允许证书 不需要配置
                .maxAge(3600);          // 暴露在请求头的有效时间
    }
}
  • 注: “*” 表示为通配符,这里如果有需要可能根据项目进行调整
  • 一般情况下为固定的格式

你可能感兴趣的:(框架基础,spring,mvc,java)