1. 程式人生 > >web後端跨域問題解決方案

web後端跨域問題解決方案

1、首先寫一個工具類

package com.custom.common.utils;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
2、在web.xml裡配置
	<!--跨域Start-->
	<filter>
		<filter-name>cors</filter-name>
		<filter-class>com.custom.common.utils.CorsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>cors</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--跨域End-->