應用CORS完成JavaWeb跨域要求成績的辦法。本站提示廣大學習愛好者:(應用CORS完成JavaWeb跨域要求成績的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是應用CORS完成JavaWeb跨域要求成績的辦法正文
之前用jsonp 處理跨域成績,如今用CORS完成跨域要求處理java 跨域成績:
重要代碼以下
package com.hy.fliter; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpStatus; /** * Created by WangShuai on 2016/7/30. */ 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; HttpServletRequest request = (HttpServletRequest) servletRequest; // 指定許可其他域名拜訪 response.setHeader("Access-Control-Allow-Origin", "*"); // 呼應類型 response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 呼應頭設置 response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); if ("OPTIONS".equals(request.getMethod())){ response.setStatus(HttpStatus.SC_NO_CONTENT); } filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
web.xml 代碼以下設置裝備擺設
<filter> <filter-name>cors</filter-name> <filter-class>com.hy.fliter.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
以上所述是小編給年夜家引見的應用CORS完成JavaWeb跨域要求成績的辦法,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!