欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Cors实现java后端完全跨域实例

程序员文章站 2024-02-19 11:35:46
这篇文章很详细的介绍了js的跨域,给出的解决方案是springboot的方式,假如不用spring boot 或者 spring版本低于4.2就需要自己实现; 参考了sp...

这篇文章很详细的介绍了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 : {
   'authorization' :'bearer iboxso9qdrhr0' 
  },
  url: 'http://localhost:8080/service/api/ping',
  type: 'get',
  datatype: 'json',
  success : function(result){
   $("#result").html(result.code);
  }
  })

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。