首頁  >  文章  >  Java  >  Cors如何實現java後端完全跨域的範例程式碼分享

Cors如何實現java後端完全跨域的範例程式碼分享

黄舟
黄舟原創
2017-05-28 09:30:141905瀏覽

本篇文章主要介紹了Cors實作java後端完全跨域實例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

http://www.jb51.net/article/114838.htm這篇文章很詳細的介紹了JS的跨域,給出的解決方案是springboot的方式,假如不用spring boot 或spring版本低於4.2就需要自己實作;

參考了spring boot的實作方式,並有所簡化,程式碼如下:

package com.lvluo.web.filter.CorsFilter;

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.springframework.http.HttpHeaders;

public class CorsFilter implements Filter {

 public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";

 public static final String OPTIONS = "OPTIONS";

 public void doFilter(ServletRequest request, ServletResponse response,
  FilterChain chain) throws IOException, ServletException {

 HttpServletRequest httpRequest = (HttpServletRequest) request;
 HttpServletResponse httpResponse = (HttpServletResponse) response;

 if (isCorsRequest(httpRequest)) {
  httpResponse.setHeader("Access-Control-Allow-Origin", "*");
  httpResponse.setHeader("Access-Control-Allow-Methods",
   "POST, GET, PUT, DELETE");
  httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
  // response.setIntHeader("Access-Control-Max-Age", 1728000);
  httpResponse
   .setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Authorization");
  if (isPreFlightRequest(httpRequest)) {
  return;
  }
 }
 chain.doFilter(request, response);
 }

 public void init(FilterConfig filterConfig) {
 }

 public void destroy() {
 }

 public boolean isCorsRequest(HttpServletRequest request) {
 return (request.getHeader(HttpHeaders.ORIGIN) != null);
 }

 /**
 * Returns {@code true} if the request is a valid CORS pre-flight one.
 */
 public boolean isPreFlightRequest(HttpServletRequest request) {
 return (isCorsRequest(request) && OPTIONS.equals(request.getMethod()) && request
  .getHeader(ACCESS_CONTROL_REQUEST_METHOD) != null);
 }
}

接著在web.xml配置filter即可

 <filter>
  <filter-name>corsFilter</filter-name>
  <filter-class>com.lvluo.web.filter.CorsFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>corsFilter</filter-name>
  <url-pattern>/api/*</url-pattern>
 </filter-mapping>

前端測試的JS程式碼,其中客戶端的

$.ajax({
  headers : {
   &#39;Authorization&#39; :&#39;Bearer iBoxSO9QdrHR0&#39; 
  },
  url: &#39;http://localhost:8080/service/api/ping&#39;,
  type: &#39;GET&#39;,
  dataType: &#39;json&#39;,
  success : function(result){
   $("#result").html(result.code);
  }
  })

以上是Cors如何實現java後端完全跨域的範例程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn