跨域问题一般发生在ajax请求不同域名服务器下的数据时,浏览器会认为ajax请求到的数据会对此时所在的域名服务器下的数据产生破坏,造成服务器崩溃。
解决跨域问题通过在servlet响应中添加"Access-Control-Allow-Origin"信息(只能解决get或post普通的跨域问题)
// 如果要返回json数据,那么对应的MIME要为 application/json
resp.setContentType("application/json;charset=utf-8");
// 告诉浏览器,我这个谁都可以拿(*表示谁都可以拿,可以设置固定的url可以拿)
resp.setHeader("Access-Control-Allow-Origin", "*");
一般前端框架都喜欢在发送ajax请求时,先发送一个options请求(测试请求),成功之后才发送我们想要发送的ajax请求,这时需要特殊的处理来解决options的跨域问题
可以创建一个过滤器专门处理options的跨域问题
package com.qf.cl.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "/*", filterName = "CrosFilter")
public class CrosFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//设置编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
/**
* 解决跨域 OPTIONS跨域
*/
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
if("OPTIONS".equals(request.getMethod())) {
response.setStatus(204); //设置状态码
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}