解决跨域问题
一、使用Filter方式
package vip.fkandy;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse)response;
//指定这个域允许跨域,如果想允许所有域,使用 “*” 号
res.addHeader("Access-Control-Allow-Origin","http://localhost:8081");
//指定允许跨域的方法,如果想允许所有方法,使用 “*” 号
res.addHeader("Access-Control-Allow-Methods","GET");
chain.doFilter(request,response);
}
}
package vip.fkandy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
//新增注册Filter代码,因为@SpringBootApplication注解包含@EnableAutoConfiguration
@Bean
public FilterRegistrationBean registerFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.addUrlPatterns("/*");//所有请求都添加过滤器
bean.setFilter(new CrosFilter());
return bean;
}
}
SpringBoot Filter使用方式参看https://blog.csdn.net/Andy2019/article/details/100567451
可以看到Response Headers里面已经添加上了Access-Control-Allow-Origin和Access-Control-Allow-Methods
注意 以上方式并不能解决带cookie的跨域请求
简单请求和非简单请求
1.简单请求
方法为:GET HEAD POST
请求header里面
无自定义头
Content-Type为以下几种:
text/plain
multipart/form-data
application/x-www-form-urlencoded
2.非简单请求
PUT,DELETE 方法的ajax请求
发送json格式的ajax请求
带自定义头的ajax请求
package vip.fkandy;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse)response;
//指定这个域允许跨域,如果想允许所有域,使用 “*” 号
res.addHeader("Access-Control-Allow-Origin","*");
//指定允许跨域的方法,如果想允许所有方法,使用 “*” 号
res.addHeader("Access-Control-Allow-Methods","*");
//非简单请求,每次发出两条请求:1条OPTIONS请求,1条数据请求
res.addHeader("Access-Control-Allow-Headers","Content-Type");
//非简单请求,设置预检命令的缓存时间为1小时
res.addHeader("Access-Control-Max-Age","3600");
chain.doFilter(request,response);
}
}
本文介绍了一种使用Spring Boot Filter实现的跨域访问控制方法,详细解释了如何配置Filter以允许特定来源和请求方法,并针对简单与非简单请求的区别进行了说明。
4万+

被折叠的 条评论
为什么被折叠?



