当前位置:首页 > 科技  > 软件

玩转Spring MVC自定义请求匹配规则

来源: 责编: 时间:2023-12-04 09:21:14 271观看
导读环境:SpringBoot2.7.12前言在Spring MVC框架中,HandlerMapping是用于将HTTP请求映射到处理器的方法的组件。当一个请求到达时,HandlerMapping会根据请求的URL和其他属性来确定哪个处理器方法应该处理该请求。在Spring MV

环境:SpringBoot2.7.12i0P28资讯网——每日最新资讯28at.com

前言

在Spring MVC框架中,HandlerMapping是用于将HTTP请求映射到处理器的方法的组件。当一个请求到达时,HandlerMapping会根据请求的URL和其他属性来确定哪个处理器方法应该处理该请求。在Spring MVC中,我们可以自定义HandlerMapping来满足特定的匹配需求。其中一个方法是使用getCustomMethodCondition()方法来自定义匹配条件。i0P28资讯网——每日最新资讯28at.com

本文将详细介绍如何使用getCustomMethodCondition()方法来自定义HandlerMapping的匹配条件。通过阅读本文,您将了解如何扩展HandlerMapping的默认行为,并使用自定义条件来匹配请求和处理器方法。i0P28资讯网——每日最新资讯28at.com

需求:我们希望根据请求header中的x-token值来匹配具体的接口。所有的接口都必须使用了自定义的注解标注。i0P28资讯网——每日最新资讯28at.com

1. 自定义请求匹配

在SpringMVC中可以通过自定义RequestMappingHandlerMapping#getCustomMethodCondition来实现此功能。i0P28资讯网——每日最新资讯28at.com

自定义请求匹配通过实现RequestCondition接口自定义规则i0P28资讯网——每日最新资讯28at.com

系统默认提供了以下RequestCondition实现i0P28资讯网——每日最新资讯28at.com

图片图片i0P28资讯网——每日最新资讯28at.com

2. 自定义匹配条件

public class CustomRequestCondition implements RequestCondition<CustomRequestCondition> {  private static final String X_TOKEN_NAME = "x-token" ;  private Method method ;  public CustomRequestCondition(Method method) {    this.method = method ;  }  // 当接口上有多个匹配规则时,进行合并操作  @Override  public CustomRequestCondition combine(CustomRequestCondition other) {    return new CustomRequestCondition(other.method) ;  }  // 核心方法:根据匹配的条件进行判断是否匹配,如果匹配则返回当前的对象,不匹配则返回null  @Override  public CustomRequestCondition getMatchingCondition(HttpServletRequest request) {    AKF akf = method.getAnnotation(AKF.class) ;    return akf != null ? buildToken(request, akf) : null ;  }  // 当有多个都满足条件的时候,进行比较具体使用哪个  @Override  public int compareTo(CustomRequestCondition other, HttpServletRequest request) {    return 0 ;  }  // 判断请求header中的信息与注解中配置的信息是否一致  private CustomRequestCondition buildToken(HttpServletRequest request, AKF akf) {    String xToken = request.getHeader(X_TOKEN_NAME) ;    if (xToken == null || xToken.length() == 0) {      return null ;    }    return xToken.equals(akf.value()) ? this : null ;  }}

3. 配置自定义HandlerMapping

public class CustomMethodConditionRequestHandlerMapping extends RequestMappingHandlerMapping {  @Override  protected RequestCondition<?> getCustomMethodCondition(Method method) {    return new CustomRequestCondition(method) ;  }}

配置自定义的HandlerMappingi0P28资讯网——每日最新资讯28at.com

@Componentpublic class CustomEndpointConfig implements WebMvcRegistrations {  public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {    return new CustomMethodConditionRequestHandlerMapping() ;  }}

通过实现WebMvcRegistrations中的getRequestMappingHandlerMapping方法覆盖系统默认的RequestMappingHandlerMapping配置实现。当然这种方式你可能失去了某些功能。这里我们可以参考默认实现来完善自定义的实现。i0P28资讯网——每日最新资讯28at.com

4. 测试接口

@RestController@RequestMapping("/conditions")public class CustomMethodConditionController {  @GetMapping("/index")  public Object index() {    return "custom method condition success" ;  }  @GetMapping("/index")  @AKF  public Object x() {    return "x method invoke" ;  }  @GetMapping("/index")  @AKF("x1")  public Object x1() {    return "x1 method invoke" ;  }  @GetMapping("/index")  @AKF("x2")  public Object x2() {    return "x2 method invoke" ;  }}

上面的接口与通常的开发配置是一致的,只是有些有接口使用了@AKF注解。这些接口中,没有@AKF注解或者没有设置@AKF值的,都不能访问,只有设置值了,且请求中携带了x-token并匹配上值了才会访问到接口。i0P28资讯网——每日最新资讯28at.com

图片i0P28资讯网——每日最新资讯28at.com

当访问其它没有@AKF注解的接口,返回404。i0P28资讯网——每日最新资讯28at.com

5. 原理

根据请求查找HandlerMethodi0P28资讯网——每日最新资讯28at.com

public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping {  protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {    String lookupPath = initLookupPath(request);    try {      // 根据请求查找匹配d饿HandlerMethod      HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);      return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);    }  }  protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {    List<Match> matches = new ArrayList<>();    // 根据请求的uri,获取相应的RequestMappingInfo(该对象对应的Controller中的每一个接口)    List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(lookupPath);    if (directPathMatches != null) {      // 根据请求找到了相应的RequestMappingInfo,则进行匹配执行相应的条件      addMatchingMappings(directPathMatches, matches, request);    }    // ...  }  private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {    for (T mapping : mappings) {      // 执行相应的条件进行匹配,比如:你在@RequestMapping中配置了header,params等相应的值      T match = getMatchingMapping(mapping, request);      if (match != null) {        matches.add(new Match(match, this.mappingRegistry.getRegistrations().get(mapping)));      }    }  }}public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMethodMapping<RequestMappingInfo> {  protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, HttpServletRequest request) {    return info.getMatchingCondition(request);  }}// RequestMappingInfopublic final class RequestMappingInfo {  // 该方法中就会根据请求request对象,判断是否当前对象符合条件  public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {    RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);    if (methods == null) {      return null;    }    ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);    if (params == null) {      return null;    }    HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);    if (headers == null) {      return null;    }    // ...    // 我们配置了自定义的,这里就会执行我们自定义的条件(必须有@AKF注解)    RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);    if (custom == null) {      // 返回null 则表示当前的RequestMappingInfo没有匹配。      // 最终如果都是返回的null,则最终返回客户端将是404      return null;    }    return new RequestMappingInfo(this.name, pathPatterns, patterns,        methods, params, headers, consumes, produces, custom, this.options);  }}

在本文中,介绍了如何自定义RequestMappingHandlerMapping。通过自定义getCustomMethodCondition()方法,我们可以根据特定的需求扩展HandlerMapping的行为,并使用自定义条件来匹配请求和处理器方法。通过这种方式,我们可以更好地控制请求的处理逻辑。i0P28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-37264-0.html玩转Spring MVC自定义请求匹配规则

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 慢聊Golang的websocket使用和实现代码分析

下一篇: 什么是软件架构需要演进的时机,你懂吗?

标签:
  • 热门焦点
  • MIX Fold3包装盒泄露 新机本月登场

    小米的全新折叠屏旗舰MIX Fold3将于本月发布,近日该机的真机包装盒在网上泄露。从图上来看,新的MIX Fold3包装盒在外观设计方面延续了之前的方案,变化不大,这也是目前小米旗舰
  • 7月安卓手机性能榜:红魔8S Pro再夺榜首

    7月份的手机市场风平浪静,除了红魔和努比亚带来了两款搭载骁龙8Gen2领先版处理器的新机之外,别的也想不到有什么新品了,这也正常,通常6月7月都是手机厂商修整的时间,进入8月份之
  • 2023 年的 Node.js 生态系统

    随着技术的不断演进和创新,Node.js 在 2023 年达到了一个新的高度。Node.js 拥有一个庞大的生态系统,可以帮助开发人员更快地实现复杂的应用。本文就来看看 Node.js 最新的生
  • 把LangChain跑起来的三个方法

    使用LangChain开发LLM应用时,需要机器进行GLM部署,好多同学第一步就被劝退了,那么如何绕过这个步骤先学习LLM模型的应用,对Langchain进行快速上手?本片讲解3个把LangChain跑起来
  • 19个 JavaScript 单行代码技巧,让你看起来像个专业人士

    今天这篇文章跟大家分享18个JS单行代码,你只需花几分钟时间,即可帮助您了解一些您可能不知道的 JS 知识,如果您已经知道了,就当作复习一下,古人云,温故而知新嘛。现在,我们就开始今
  • 一篇文章带你了解 CSS 属性选择器

    属性选择器对带有指定属性的 HTML 元素设置样式。可以为拥有指定属性的 HTML 元素设置样式,而不仅限于 class 和 id 属性。一、了解属性选择器CSS属性选择器提供了一种简单而
  • 签约井川里予、何丹彤,单视频点赞近千万,MCN黑马永恒文希快速崛起!

    来源:视听观察永恒文希传媒作为一家MCN公司,说起它的名字来,可能大家会觉得有点儿陌生,但是说出来下面一串的名字之后,或许大家就会感到震惊,原来这么多网红,都签约这家公司了。根
  • 花7万退货退款无门:谁在纵容淘宝珠宝商家造假?

    来源:极点商业作者:杨铭在淘宝购买珠宝玉石后,因为保证金不够赔付,店铺关闭,退货退款难、维权无门的比比皆是。&ldquo;提供相关产品鉴定证书,支持全国复检,可以30天无理由退换货。&
  • 利用职权私自解除被封帐号 Meta开除20多名员工

    11月18日消息,据外媒援引知情人士表示,过去一年时间内,Facebook母公司Meta解雇或处罚了20多名员工以及合同工,指控这些人通过内部系统以不当方式重置用户帐号,其
Top