在http
请求中,默认只能在同一个域中进行访问,如果访问不同的域,则会被认为是非法操作,浏览器会提示No 'Access-Control-Allow-Origin'
错误。
**注: ** 所谓 域
就是网址名称。如https://www.baidu.com
,它的域就是baidu.com
。如果我在baidu.com
下面想访问google.com
下面的资源,这就叫跨域。
前端可以通过使用jsonp
执行跨域请求。这里不多做解释。
java
服务器可以对所有的请求进行拦截,通过设置response
对象的header
实现跨域。
response
需要设置的header和值的对应关系
header 名 | header 值 |
---|---|
Access-Control-Allow-Origin | * |
Access-Control-Allow-Methods | POST, GET, DELETE, OPTIONS, DELETE, PUT |
Access-Control-Allow-Headers | Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token |
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 允许跨域过滤器
*
* @author zhoutaotao
* @date 2019/5/31
*/
public class AllowOriginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}