springboot如何為web層添加統(tǒng)一請求前綴
如何為web層添加統(tǒng)一請求前綴
配置文件方式
application.properties全局配置文件配置:
server.servlet.context-path=/api
實(shí)現(xiàn)WebMvcConfigurer接口
重寫configurePathMatch()方法,代碼:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {? ??
? ? /**
? ? ?* 請求路徑添加統(tǒng)一前綴
? ? ?*
? ? ?* @param configurer
? ? ?*/
? ? @Override
? ? public void configurePathMatch(PathMatchConfigurer configurer) {
? ? ? ? configurer.addPathPrefix("/api", c -> c.isAnnotationPresent(RestController.class) || c.isAnnotationPresent(Controller.class));
? ? }
}上面為controller層所有都添加了統(tǒng)一前綴,如果不同版本想使用不同的請求前綴,可優(yōu)化如下:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {? ??
? ? /**
? ? ?* 請求路徑添加統(tǒng)一前綴
? ? ?*
? ? ?* @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
@RequestMapping
public @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訪問頁面出現(xiàn)多余前綴和后綴情況
頁面中出現(xiàn)hello.jsp

解決方法
去掉servlet中的前綴后綴配置項(xiàng)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis多對多關(guān)聯(lián)實(shí)戰(zhàn)教程(推薦)
下面小編就為大家?guī)硪黄猰ybatis多對多關(guān)聯(lián)實(shí)戰(zhàn)教程(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
詳解Java如何實(shí)現(xiàn)多線程步調(diào)一致
本章節(jié)主要講解另外兩個線程同步器:CountDownLatch和CyclicBarrier的用法,使用場景以及實(shí)現(xiàn)原理,感興趣的小伙伴可以了解一下2023-07-07
Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
springboot 如何重定向redirect 并隱藏參數(shù)
這篇文章主要介紹了springboot 如何重定向redirect 并隱藏參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

