springboot跨域处理

我们在开发的过程中,有人可能会遇到跨域问题,如下所示

这里使用的sosoapi作为测试

这里我为大家提供2种解决方式,一种是过滤器的方式,在过滤器之中添加允许跨域,新建一个java文件,代码如下所示

package com.example.fw.base;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import com.example.fw.Application;

/**
 * 使用注解标注过滤器
 * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器
 * 属性filterName声明过滤器的名称,可选
 * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
 * 
 */
@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {

    public void destroy() {
    	Application.out("过滤器销毁");//当服务器关闭时调用
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    	HttpServletResponse resp = (HttpServletResponse)response;
//    	Application.out("-----------------------跨域处理-------------------------------");
    	//"*"存在风险,建议指定可信任的域名来接收响应信息,如"http://www.sosoapi.com"
    	resp.addHeader("Access-Control-Allow-Origin", "*");
    	//如果存在自定义的header参数,需要在此处添加,逗号分隔
    	resp.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, "
    			+ "If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, "
    			+ "Content-Type, X-E4M-With");
    	//允许跨域的请求方式
    	resp.addHeader("Access-Control-Allow-Methods", "GET, POST"); 
    	//是否允许发送Cookie
    	resp.addHeader("Access-Control-Allow-Credentials", "true");
    	chain.doFilter(request, response);
  
    }

    public void init(FilterConfig config) throws ServletException {
    	Application.out("过滤器初始化");//当服务器启动时调用
    }


}

 

@WebFilter注解是spring提供的声明注解,告诉springboot这个类是我们的过滤器,这个注解有很多参数,有兴趣的朋友可以自己去了解,我这里就列举了2个

filterName:指定过滤器的 name 属性,等价于以前我们在web.xml里面配置的 <filter-name>

urlPatterns:要过滤的url,*代表所有

我们来测试一下

发现还是这样,并没有解决,原因是因为这个模式还需要在启动文件,xxxApplication里面加上对应的注解

代码如下所示

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

@ServletComponentScan

这个注解告诉springboot,我们的全局上下文之中有Servlet、Filter、Listener的一种

我们在测试

 

这就成功了,当然,这属于我们自己的方式,springboot内部其实也为我们提供了解决方式,叫做CORSConfiguration

新建一个java类,继承自WebMvcConfiugrationAdaper,重写addCorsMappings方法,代码如下

@Configuration
public class ExceptionHandle extends WebMvcConfiugrationAdaper{
		public void addCorsMappings(CorsRegistry mCorsRegistry){
			mCorsRegistry.addMapping("/**")
					.allowedMethods("GET","POST")//可以用*
						.allowedOrigins("*")
					.allowedHeaders("*");
		}
  }

原理其实都是一样的,只是springboot的更简化

addMapping:允许跨域的路径

allowedMethods:允许跨域的方法

allowedOrigins:允许跨域的域名(允许哪个域名跨域访问)

allowedHeaders:可以自定义的请求头

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值