You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ssgl/zsq/MyWebMvcConfigurer.java

42 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.yanzhen.framework.mvc; // 定义包名
import org.springframework.context.annotation.Bean; // 导入@Bean注解
import org.springframework.context.annotation.Configuration; // 导入@Configuration注解
import org.springframework.web.cors.CorsConfiguration; // 导入CorsConfiguration类
import org.springframework.web.cors.CorsConfigurationSource; // 导入CorsConfigurationSource接口
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; // 导入UrlBasedCorsConfigurationSource类
import org.springframework.web.filter.CorsFilter; // 导入CorsFilter类
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; // 导入InterceptorRegistry类
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; // 导入WebMvcConfigurer接口
@Configuration // 标记该类为配置类
public class MyWebMvcConfigurer implements WebMvcConfigurer { // 实现WebMvcConfigurer接口
@Bean // 将方法返回的对象注册为Spring容器中的Bean
public TokenInterceptor tokenInterceptor(){ // 定义tokenInterceptor方法返回TokenInterceptor对象
return new TokenInterceptor(); // 创建并返回TokenInterceptor实例
}
@Override // 重写父类的方法
public void addInterceptors(InterceptorRegistry registry) { // 定义addInterceptors方法参数为InterceptorRegistry对象
registry.addInterceptor(tokenInterceptor()) // 添加自定义拦截器
.addPathPatterns("/**") // 设置拦截所有路径
.excludePathPatterns("/login"); // 排除登录路径不拦截
}
//使用CorsFilter解决跨域的问题
@Bean // 将方法返回的对象注册为Spring容器中的Bean
public CorsFilter corsFilter(){ // 定义corsFilter方法返回CorsFilter对象
CorsConfiguration corsConfiguration = new CorsConfiguration(); // 创建CorsConfiguration实例
//允许跨域请求的域名
corsConfiguration.addAllowedOrigin("*"); // 允许所有域名进行跨域请求
corsConfiguration.addAllowedMethod("*"); // 允许所有HTTP方法进行跨域请求
//允许任何头部
corsConfiguration.addAllowedHeader("*"); // 允许所有头部信息进行跨域请求
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); // 创建UrlBasedCorsConfigurationSource实例
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration); // 注册跨域配置到URL模式
CorsFilter corsFilter = new CorsFilter(urlBasedCorsConfigurationSource); // 创建CorsFilter实例
return corsFilter; // 返回CorsFilter实例
}
}