前后端分离开发解决前端静态资源跨域请求问题

时间:2022-08-28 12:02:47

前端静态资源发起请求时首先会发送一个域请求,后端通过后再次发起get、post请求

使用过滤器对域请求授权,这里授权了一个特殊的token请求字段,可以根据自己的业务添加请求字段。

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class HttpFilter
 */
public class HttpFilter implements Filter {

    /**
     * Default constructor. 
     */
    public HttpFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse resp=(HttpServletResponse)response;
		HttpServletRequest rep = (HttpServletRequest) request;
		resp.setHeader("Access-Control-Allow-Origin", rep.getHeader("Origin"));
		resp.setHeader("Access-Control-Allow-Methods", "POST, GET,PUT, OPTIONS, DELETE,PUT");
		resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorizationaccept, origin, content-type, token");
		//允许跨域请求中携带cookie
		resp.setHeader("Access-Control-Allow-Credentials","true");
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

相关文章