Boot 解决跨域 及后续传参问题

本人用此方法解决 跨域 及 解决跨域后传参问题

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class HttpFilterConfig {

	@Bean
	public FilterRegistrationBean<CorsFilter> corsFilter() {
		CorsConfiguration corsConfig = new CorsConfiguration();
		corsConfig.setAllowCredentials(true);
		corsConfig.addAllowedOrigin(CorsConfiguration.ALL);
		corsConfig.addAllowedMethod(CorsConfiguration.ALL);
		corsConfig.addAllowedHeader(CorsConfiguration.ALL);
		//默认可不设置这个暴露的头。这个为了安全问题,不能使用*。设置成*,后面会报错:throw new IllegalArgumentException("'*' is not a valid exposed header value");
		//corsConfig.addExposedHeader("");
		corsConfig.setMaxAge(3600L);
		
		UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
		configSource.registerCorsConfiguration("/**", corsConfig);
		
		FilterRegistrationBean<CorsFilter> corsBean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(configSource));
		corsBean.setName("crossOriginFilter");
		corsBean.setOrder(0);//这个顺序也有可能会有影响,尽量设置在拦截器前面
		return corsBean;
	}
	
	
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 2 中,你可以使用以下方法来解决问题: 1. 使用 `@CrossOrigin` 注解:在控制器类或具体的请求处理方法上添加 `@CrossOrigin` 注解来启用访问。你可以使用该注解来指定允许访问的来源、方法和自定义的头信息等。 ```java import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = "http://example.com") public class MyController { @GetMapping("/api/data") public String getData() { // 处理请求 } } ``` 2. 使用全局配置类:创建一个全局配置类来配置访问的规则,并注册为一个 Bean。 ```java import org.springframework.context.annotation.Bean; 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 CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } } ``` 以上方法都可以实现访问的配置。你可以根据具体需求选择合适的方法来解决问题。请确保在安全性和实际需求之间做出适当的权衡和配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值