springboot怎么为web层添加统一请求前缀
这篇文章主要介绍“springboot怎么为web层添加统一请求前缀”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么为web层添加统一请求前缀”文章能帮助大家解决问题。
如何为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解决方法去掉servlet中的前缀后缀配置项
关于“springboot怎么为web层添加统一请求前缀”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。