自动化立体仓库 - WMS系统
skyouc
21 小时以前 9e6d4880ca1ce6ae5cb9b9dc1b865f0ee9f65fe8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.zy.common.config;
 
import com.zy.common.constant.MesConstant;
import com.zy.common.utils.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Created by vincent on 2019-06-13
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    @Autowired
    private AdminInterceptor adminInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminInterceptor)
                .addPathPatterns("/**")
        ;
    }
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 使用 allowedOriginPatterns 而不是 allowedOrigins
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
 
    /**
     * 方式二:使用 Filter(更全面,优先级更高)
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
 
        // 允许所有域名
        config.addAllowedOrigin("*");
 
        // 允许任何头
        config.addAllowedHeader("*");
 
        // 允许任何方法(GET, POST, PUT, DELETE, OPTIONS等)
        config.addAllowedMethod("*");
 
        // 允许凭证(如果需要cookie等凭证,设置为true,但需要指定具体域名)
        config.setAllowCredentials(false);
 
        // 预检请求的有效期,单位为秒
        config.setMaxAge(3600L);
 
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
 
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
 
        // 设置优先级最高
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
 
        return bean;
    }
 
 
}