Cors实现java后端完全跨域实例
https://www.nhooo.com/article/114838.htm这篇文章很详细的介绍了JS的跨域,给出的解决方案是springboot的方式,假如不用springboot或者spring版本低于4.2就需要自己实现;
参考了springboot的实现方式,并有所简化,代码如下:
packagecom.lvluo.web.filter.CorsFilter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.springframework.http.HttpHeaders; publicclassCorsFilterimplementsFilter{ publicstaticfinalStringACCESS_CONTROL_REQUEST_METHOD="Access-Control-Request-Method"; publicstaticfinalStringOPTIONS="OPTIONS"; publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse, FilterChainchain)throwsIOException,ServletException{ HttpServletRequesthttpRequest=(HttpServletRequest)request; HttpServletResponsehttpResponse=(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); } publicvoidinit(FilterConfigfilterConfig){ } publicvoiddestroy(){ } publicbooleanisCorsRequest(HttpServletRequestrequest){ return(request.getHeader(HttpHeaders.ORIGIN)!=null); } /** *Returns{@codetrue}iftherequestisavalidCORSpre-flightone. */ publicbooleanisPreFlightRequest(HttpServletRequestrequest){ 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':'BeareriBoxSO9QdrHR0' }, url:'http://localhost:8080/service/api/ping', type:'GET', dataType:'json', success:function(result){ $("#result").html(result.code); } })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。