当前位置: 首页 > 科技观察

SpringMVC进阶知识点:自定义请求匹配路径

时间:2023-03-13 20:27:25 科技观察

环境:springboot2.2.10.RELEASE自定义请求匹配想根据请求中header['x-token']的不同取值调用不同的接口。接口请求地址相同,根据不同的header信息调用不同的执行方法。在SpringMVC中,可以通过自定义RequestMappingHandlerMapping#getCustomMethodCondition来实现该功能。自定义请求匹配是通过实现RequestCondition接口实现的。自定义规则系统默认提供如下RequestCondition来实现自定义匹配条件。/当接口上有多个匹配规则时,执行合并操作@OverridepublicCustomRequestConditioncombine(CustomRequestConditionother){returnnewCustomRequestCondition(other.method);}//核心方法:根据匹配条件判断是否匹配,如果匹配则返回当前对象,如果没有匹配则返回null@OverridepublicCustomRequestConditiongetMatchingCondition(HttpServletRequestrequest){AKFakf=method.getAnnotation(AKF.class);returnakf!=null?buildToken(request,akf):null;}//有多个条件时满足条件的,继续比较使用哪个@OverridepublicintcompareTo(CustomRequestConditionother,HttpServletRequestrequest){return0;}//判断请求头中的信息是否与注解中配置的信息一致privateCustomRequestConditionbuildToken(HttpServletRequestrequest,AKFakf){StringxTokenTO=request.getEN_Header(NAXTokenTO)==null||xToken。长度()==0){重新turnnull;}returnxToken.equals(akf.value())?this:null;}}自定义HandlerMappingpublicclassCustomMethodConditionRequestHandlerMappingextendsRequestMappingHandlerMapping{@OverrideprotectedRequestConditiongetCustomMethodCondition(Methodmethod){returnnewCustomRequestCondition(method);}}配置自定义的HandlerMapping@ConfigurationpublicclassCustomEndpointConfigextendsWebMvcConfigurationSupport{@OverrideprotectedRequestMappingHandlerMappingcreateRequestMappingHandlerMapping(){returnnewCustomMethodConditionRequestHandlerMapping();}}注册HandlerMapping我们也可以使用@Bean,但是这种方式会让你在容器启动的时候定义多个相同的接口地址,会报错,@Bean的方式就是报错向容器注册一个HandlerMapping对象;而上面的方法是替换系统默认的RequestMappingHandlerMapping对象。这两种方法是不同的。一是添加一个HandlerMapping,二是替换系统默认的。测试接口@RestController@RequestMapping("/conditions")}@GetMapping("/index")@AKF("x1")publicObjectx1(){return"x1methodinvoke";}@GetMapping("/index")@AKF("x2")publicObjectx2(){return"x2methodinvoke";}}以上接口地址完全相关,只是有的有@AKF注解有的没有。如果通过@Bean注册一个HandlerMapping,如果多个请求路径相同,会报如下错误:GET/conditions/index}:已经存在'customMethodConditionController'beanmethodcom.pack.controller.CustomMethodConditionController#index()mapped.atorg.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.validateMethodMapping(AbstractHandlerMethodMapping.web.java-java-636:636)~[spring9.RELEASE.jar:5.2.9.RELEASE]atorg.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:603)~[spring-webmvc-5.2.9.RELEASE.jar:5.2。9.RELEASE]在上面的请求中,如果请求中没有携带x-token信息或者value值不匹配,请求就会404。