springboot怎么为web层添加统一请求前缀
发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章主要介绍"springboot怎么为web层添加统一请求前缀"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"springboot怎么为web层添加统一请
千家信息网最后更新 2026年11月03日springboot怎么为web层添加统一请求前缀
这篇文章主要介绍"springboot怎么为web层添加统一请求前缀"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"springboot怎么为web层添加统一请求前缀"文章能帮助大家解决问题。
如何为web层添加统一请求前缀
配置文件方式
application.properties全局配置文件配置:
server.servlet.context-path=/api
实现WebMvcConfigurer接口
重写configurePathMatch()方法,代码:
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { /** * 请求路径添加统一前缀 * * @param configurer */ @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix("/api", c -> c.isAnnotationPresent(RestController.class) || c.isAnnotationPresent(Controller.class)); }}上面为controller层所有都添加了统一前缀,如果不同版本想使用不同的请求前缀,可优化如下:
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { /** * 请求路径添加统一前缀 * * @param configurer */ @Override public void configurePathMatch(PathMatchConfigurer configurer) { 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:
import org.springframework.core.annotation.AliasFor;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.lang.annotation.*; @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@RestController@RequestMappingpublic @interface ApiRestController { /** * Alias for {@link RequestMapping#name}. */ @AliasFor(annotation = RequestMapping.class) String name() default ""; /** * Alias for {@link RequestMapping#value}. */ @AliasFor(annotation = RequestMapping.class) String[] value() default {}; /** * Alias for {@link RequestMapping#path}. */ @AliasFor(annotation = RequestMapping.class) String[] path() default {};}使用:
@ApiRestController("/demo")public class DemoController extends BaseController{}这样请求地址就成了:http://localhost:8080/api/demo
spring web访问页面出现多余前缀和后缀情况
页面中出现hello.jsp
解决方法
去掉servlet中的前缀后缀配置项
关于"springboot怎么为web层添加统一请求前缀"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。
前缀
统一
配置
不同
方法
注解
知识
后缀
文件
行业
路径
页面
实用
代码
全局
内容
地址
实用性
实际
情况
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
咖啡豆
互联网科技公司
新华互联网科技
互联网核心科技是什么
互联网科技logo
伴你行互联网科技有限公司
卓越科技互联网 招聘
蓝色互联网科技
深圳市运趣互联网科技有限公司
互联网之后的科技是什么
互联网科技中介
金融科技与互联网金融相同和不同
宁夏众和广鑫互联网科技有限公司
上海宁丞科技互联网
新兴科技互联网创新大赛颁奖典礼
世界互联网领先科技成果获奖
云南省自由互联网科技有限公司
浙南科技城互联网大厦招聘
互联网的黑科技实验室
武汉亿视互联网科技有限公司
有格互联网科技
云信互联网科技有限公司
金诺互联网科技
互联网科技战争
麻工互联网科技
互联网科技公司发展
互联网金融 科技创新
互联网科技汛
互联网科技商业
山东大美朱楼互联网科技有限公司