配置tomcat7容許跨域訪問

在web.xml文件中加入如下內容:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>cn.iqoo.api.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

便可支持js的跨域請求了.java

 

第二web

/*
 * @Project_Name: iqoo-parent
 * @File_Name: CorsFilter
 * @Package_Name: cn.iqoo.api.filter
 * @Date: 17-3-2 下午10:41
 * @Creator: jonath
 * @Line: ----------------------------------------
 */
package cn.iqoo.api.filter;

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

/**
 * TODO:
 *
 * @author: jonath
 * @date: 17-3-2
 */
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 httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
相關文章
相關標籤/搜索