1.首先由於服務器端會先發送一個option請求到後臺 在後臺返回一個post給頁面 頁面在處理post請求給接口 java
2.先寫一個過濾器, 咱們本身定義一個過濾器web
package com.adtime.dsp.web.controller;spring
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.HttpServletResponse;服務器
import org.springframework.stereotype.Component;app
/**
* Created by kangb on 2016/5/10.
*/cors
public class myCORSFilter implements Filter {ide
@Override
public void init(FilterConfig filterConfig) throws ServletException {post
}url
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
String origin = (String) servletRequest.getRemoteHost()+":"+servletRequest.getRemotePort();
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,Authorization");
response.setHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
3.在web.xml裏面配置過濾器
<!-- options 403 -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.adtime.dsp.web.controller.myCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4.過濾器會自動過濾options請求 而後就能夠直接跨域訪問接口了