色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術文章
文章詳情頁

Spring @CrossOrigin 注解原理實現

瀏覽:38日期:2023-08-28 16:39:50

現實開發中,我們難免遇到跨域問題,以前筆者只知道jsonp這種解決方式,后面聽說spring只要加入@CrossOrigin即可解決跨域問題。本著好奇的心里,筆者看了下@CrossOrigin 作用原理,寫下這篇博客。

先說原理:其實很簡單,就是利用spring的攔截器實現往response里添加 Access-Control-Allow-Origin等響應頭信息,我們可以看下spring是怎么做的

注:這里使用的spring版本為5.0.6

我們可以先往RequestMappingHandlerMapping 的initCorsConfiguration方法打一個斷點,發現方法調用情況如下

Spring @CrossOrigin 注解原理實現

如果controller在類上標了@CrossOrigin或在方法上標了@CrossOrigin注解,則spring 在記錄mapper映射時會記錄對應跨域請求映射,代碼如下

RequestMappingHandlerMappingprotected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) { HandlerMethod handlerMethod = createHandlerMethod(handler, method); Class<?> beanType = handlerMethod.getBeanType(); //獲取handler上的CrossOrigin 注解 CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class); //獲取handler 方法上的CrossOrigin 注解 CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class); if (typeAnnotation == null && methodAnnotation == null) { //如果類上和方法都沒標CrossOrigin 注解,則返回一個null return null; } //構建一個CorsConfiguration 并返回 CorsConfiguration config = new CorsConfiguration(); updateCorsConfig(config, typeAnnotation); updateCorsConfig(config, methodAnnotation); if (CollectionUtils.isEmpty(config.getAllowedMethods())) { for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) { config.addAllowedMethod(allowedMethod.name()); } } return config.applyPermitDefaultValues(); }

將結果返回到了AbstractHandlerMethodMapping#register,主要代碼如下

CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping); if (corsConfig != null) {//會保存handlerMethod處理跨域請求的配置 this.corsLookup.put(handlerMethod, corsConfig); }

當一個跨域請求過來時,spring在獲取handler時會判斷這個請求是否是一個跨域請求,如果是,則會返回一個可以處理跨域的handler

AbstractHandlerMapping#getHandler HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request); //如果是一個跨域請求if (CorsUtils.isCorsRequest(request)) { //拿到跨域的全局配置 CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request); //拿到hander的跨域配置 CorsConfiguration handlerConfig = getCorsConfiguration(handler, request); CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig); //處理跨域(即往響應頭添加Access-Control-Allow-Origin信息等),并返回對應的handler對象 executionChain = getCorsHandlerExecutionChain(request, executionChain, config); }

我們可以看下如何判定一個請求是一個跨域請求,

public static boolean isCorsRequest(HttpServletRequest request) {//判定請求頭是否有Origin 屬性即可 return (request.getHeader(HttpHeaders.ORIGIN) != null); }

再看下getCorsHandlerExecutionChain 是如何獲取一個handler

protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request, HandlerExecutionChain chain, @Nullable CorsConfiguration config) { if (CorsUtils.isPreFlightRequest(request)) { HandlerInterceptor[] interceptors = chain.getInterceptors(); chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors); } else { //只是給執行器鏈添加了一個攔截器 chain.addInterceptor(new CorsInterceptor(config)); } return chain; }

也就是在調用目標方法前會先調用CorsInterceptor#preHandle,我們觀察得到其也是調用了corsProcessor.processRequest方法,我們往這里打個斷點

processRequest方法的主要邏輯如下

public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) throws IOException { //.... //調用了自身的handleInternal方法 return handleInternal(serverRequest, serverResponse, config, preFlightRequest); }protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response, CorsConfiguration config, boolean preFlightRequest) throws IOException { String requestOrigin = request.getHeaders().getOrigin(); String allowOrigin = checkOrigin(config, requestOrigin); HttpHeaders responseHeaders = response.getHeaders(); responseHeaders.addAll(HttpHeaders.VARY, Arrays.asList(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); if (allowOrigin == null) { logger.debug('Rejecting CORS request because ’' + requestOrigin + '’ origin is not allowed'); rejectRequest(response); return false; } HttpMethod requestMethod = getMethodToUse(request, preFlightRequest); List<HttpMethod> allowMethods = checkMethods(config, requestMethod); if (allowMethods == null) { logger.debug('Rejecting CORS request because ’' + requestMethod + '’ request method is not allowed'); rejectRequest(response); return false; } List<String> requestHeaders = getHeadersToUse(request, preFlightRequest); List<String> allowHeaders = checkHeaders(config, requestHeaders); if (preFlightRequest && allowHeaders == null) { logger.debug('Rejecting CORS request because ’' + requestHeaders + '’ request headers are not allowed'); rejectRequest(response); return false; } //設置響應頭 responseHeaders.setAccessControlAllowOrigin(allowOrigin); if (preFlightRequest) { responseHeaders.setAccessControlAllowMethods(allowMethods); } if (preFlightRequest && !allowHeaders.isEmpty()) { responseHeaders.setAccessControlAllowHeaders(allowHeaders); } if (!CollectionUtils.isEmpty(config.getExposedHeaders())) { responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders()); } if (Boolean.TRUE.equals(config.getAllowCredentials())) { responseHeaders.setAccessControlAllowCredentials(true); } if (preFlightRequest && config.getMaxAge() != null) { responseHeaders.setAccessControlMaxAge(config.getMaxAge()); } //刷新 response.flush(); return true; }

至此@CrossOrigin的使命就完成了,說白了就是用攔截器給response添加響應頭信息而已

到此這篇關于Spring @CrossOrigin 注解原理實現的文章就介紹到這了,更多相關Spring @CrossOrigin 注解內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 99久久成人国产精品免费 | 91精品国产色综合久久不 | 一个人免费看的www 一及 片日本 | 在线播放性xxx欧美 在线播放亚洲视频 | 在线亚洲一区二区 | 神马三级我不卡 | 亚洲性无码av在线 | 久久久久久国产视频 | 欧美一级毛片免费看视频 | 欧美韩国xxx | 国产视频高清在线观看 | 最新精品在线视频 | 日本三级香港三级三级人 | 天干夜天天夜天干天ww | 久久视频精品36线视频在线观看 | 国产成人精品福利站 | 国产在线观看一区精品 | 亚洲骚片 | 国产日韩不卡免费精品视频 | 最新精品国产 | 免费观看一级欧美在线视频 | 成人综合在线视频免费观看 | 欧美一级高清片在线 | 超级香蕉97视频在线观看一区 | 最新中文字幕乱码在线 | m男亚洲一区中文字幕 | 国产在线乱子伦一区二区 | 欧洲一级鲁丝片免费 | 69久成人做爰视频 | 欧美a一级 | 欧美高清正版在线 | 亚洲逼 | 国产精品视频免费播放 | 国产午夜人做人视频羞羞 | 日本精品一区二区三区在线视频一 | 69国产成人综合久久精品91 | 手机看片欧美 | 久草视频中文 | 欧美一区二区视频三区 | 国产一区二区免费在线观看 | 欧美在线高清视频播放免费 |