Javaweb下的跨域問題

       因爲瀏覽器同源訪問的限制,前端在使用ajax進行請求時會出現跨域問題,只要端口不一樣,主機不一樣服務調用必定跨域,在spring裏面,有個@CrossOrigin註解能夠解決跨域問題,可是在個人實踐中發現並很差用前幾天用spring boot寫後臺出現跨域,以前有用的解決方案所有失效,很玄學的問題。如今我想用一種通用的解決方案來實現:html

public class OriginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 處理跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        httpServletResponse.setHeader("X-Powered-By", "Tomcat");
        httpServletResponse.setHeader("Content-Type", "text/html;charset=UTF-8");
        httpServletResponse.setHeader("maxAge", "10000");

        request.setAttribute("Access-Control-Request-Headers", "*");
        filterChain.doFilter(request, response);
    }
}

若是是springboot還須要在本類上加註解前端

@Component
@WebFilter(urlPatterns = "/", filterName = "myOriginFilter")
@Order(1)//指定過濾器的執行順序,值越大越靠後執行

主類上加上@ServletComponentScanjava

如果普通javaweb項目寫配置文件就好web

我的看法:跨域這種安全性問題真的不能交給前端去控制,咱們的前端一直想去用jsonp去解決跨域被我擋回去了,前端真的控制不了安全問題ajax

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息