cjl
2023-08-23 b6f14a410e20cdecff99bde338127b42780a343b
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
package com.moral.api.config.Interceptor;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
 
import java.util.ArrayList;
 
import com.moral.api.interceptor.WebInterceptor;
 
@Configuration
public class WebAppConfiguration implements WebMvcConfigurer {
 
    //读取不需拦截路径
    @Bean
    @ConfigurationProperties("mvc.interceptor.exclude")
    public ArrayList<String> getExcludePath() {
        return new ArrayList<>();
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration regisration = registry.addInterceptor(new WebInterceptor());
        ArrayList<String> excludePath = getExcludePath();
        regisration.addPathPatterns("/**/**");//设置拦截路径
        regisration.excludePathPatterns(excludePath);//设置不拦截路径
    }
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOrigins("*")
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
 
    /**
     * 添加静态资源文件,外部可以直接访问地址
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        try {
            ApplicationHome h = new ApplicationHome(getClass());
            //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
            String path = h.getSource().getParentFile().toString() + "/static/";
            registry.addResourceHandler("/static/**").addResourceLocations("file:" + path);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}