java-拦截器实现跨域支持

package com.test.test.conf;



import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;

//拦截器添加跨域支持(如果是web.xml配置拦截器,请将@component删除)
@Component
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 response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

以上是注解的配置方式

下面是web.xml的配置方式


<filter>
    <filter-name>crossoriginfilter-name>
    <filter-class>com.test.test.crossoriginfilter-class>
filter>
<filter-mapping>
    <filter-name>crossoriginfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

你可能感兴趣的:(java-拦截器实现跨域支持)