- 請求過濾器:
/**
* OncePerRequestFilter保證在任何Servlet容器中都是一個請求只執行一次的過濾器。
*/
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties");
//容許的 客戶端域名
resp.addHeader("Access-Control-Allow-Origin", props.getProperty("cors.allowed-origins"));
//容許的 方法名
resp.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods"));
//容許服務端訪問的客戶端請求頭,多個請求頭用逗號分割,例如:Content-Type
resp.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
//預檢驗請求時間
resp.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min
resp.addHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
}
}
- web.xml中配置跨域過濾器:
<!--配置跨域請求的過濾器-->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.niewj.cors.CrossFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 過濾器中的屬性配置以下:
#跨域請求CORS全局配置屬性值
#容許訪問的客戶端域名,例如:http://web.xxx.com
cors.allowed-origins=http://front.xx.com
#容許訪問的方法名
cors.allowed-methods=POST, GET, OPTIONS, DELETE
#容許服務端訪問的客戶端請求頭,多個請求頭用逗號分割,例如:Content-Type
cors.allowed-headers=Content-Type
#容許客戶端訪問的服務端響應頭
cors.exposed-headers=
#是否容許請求帶有驗證信息,若要獲取客戶端域下的cookie時,須要將其設置爲true
cors.allow-credentials=true
cors.max-age=1800
因爲jsonp只支持GET方式的請求,因此這種方式比較推薦。