java项目中使用Cors实现后端跨域的法

发布时间:2020-11-20 16:36:01 作者:Leah
来源:亿速云 阅读:220

今天就跟大家聊聊有关java项目中使用Cors实现后端跨域的法,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

代码如下:

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 : {
   'Authorization' :'Bearer iBoxSO9QdrHR0' 
  },
  url: 'http://localhost:8080/service/api/ping',
  type: 'GET',
  dataType: 'json',
  success : function(result){
   $("#result").html(result.code);
  }
  })

看完上述内容,你们对java项目中使用Cors实现后端跨域的法有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. CORS跨域请求:前后端分离
  2. 跨域CORS

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java cors ava

上一篇:利用SpringBoot实现一个跳转支付功能

下一篇:Android项目中出现TextView排版参差不齐如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》