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

网友投稿 227 2023-05-12


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

//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即可

corsFilter

com.lvluo.web.filter.CorsFilter

corsFilter

/api/*

前端测试的JS代码,其中客户端的

$.ajax({

headers : {

'Authorization' :'Bearer iBoxSO9QdrHR0'

},

url: 'http://localhost:8080/service/api/ping',

type: 'GET',

dataType: 'json',

success : function(result){

$("#result").html(http://result.code);

}

})


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring整合redis以及使用RedisTemplate的方法
下一篇:Spring Boot Web应用开发 CORS 跨域请求支持
相关文章

 发表评论

暂时没有评论,来抢沙发吧~