springboot怎么为web层添加统一请求前缀(springboot,web,开发技术)

时间:2024-05-04 10:11:31 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

如何为web层添加统一请求前缀

配置文件方式

application.properties全局配置文件配置:

server.servlet.context-path=/api

实现WebMvcConfigurer接口

重写configurePathMatch()方法,代码:

@ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{/***请求路径添加统一前缀**@paramconfigurer*/@OverridepublicvoidconfigurePathMatch(PathMatchConfigurerconfigurer){configurer.addPathPrefix("/api",c->c.isAnnotationPresent(RestController.class)||c.isAnnotationPresent(Controller.class));}}

上面为controller层所有都添加了统一前缀,如果不同版本想使用不同的请求前缀,可优化如下:

@ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{/***请求路径添加统一前缀**@paramconfigurer*/@OverridepublicvoidconfigurePathMatch(PathMatchConfigurerconfigurer){configurer.addPathPrefix("/api",c->c.isAnnotationPresent(ApiRestController.class)).addPathPrefix("/api/v2",c->c.isAnnotationPresent(ApiV2RestController.class));}}

对有 @ApiRestController 注解的 controller 添加 /api 前缀,对有@ApiV2RestController 注解的controller添加 /api/v2 前缀。

@ApiRestController 和 @ApiV2RestController 是自定义注解,继承自 @RestController:

importorg.springframework.core.annotation.AliasFor;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.lang.annotation.*;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@RestController@RequestMappingpublic@interfaceApiRestController{/***Aliasfor{@linkRequestMapping#name}.*/@AliasFor(annotation=RequestMapping.class)Stringname()default"";/***Aliasfor{@linkRequestMapping#value}.*/@AliasFor(annotation=RequestMapping.class)String[]value()default{};/***Aliasfor{@linkRequestMapping#path}.*/@AliasFor(annotation=RequestMapping.class)String[]path()default{};}

使用:

@ApiRestController("/demo")publicclassDemoControllerextendsBaseController{}

这样请求地址就成了:http://localhost:8080/api/demo

spring web访问页面出现多余前缀和后缀情况

页面中出现hello.jsp

springboot怎么为web层添加统一请求前缀

解决方法

去掉servlet中的前缀后缀配置项

springboot怎么为web层添加统一请求前缀

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:springboot怎么为web层添加统一请求前缀的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:如何使用OpenGL Shader实现彩虹条纹效果下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18