温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2022-02-18 10:48:10 来源:亿速云 阅读:579 作者:iii 栏目:开发技术

这篇文章主要介绍“springboot怎么为web层添加统一请求前缀”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么为web层添加统一请求前缀”文章能帮助大家解决问题。

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

配置文件方式

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

server.servlet.context-path=/api

实现WebMvcConfigurer接口

重写configurePathMatch()方法,代码:

@Configuration
public 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层所有都添加了统一前缀,如果不同版本想使用不同的请求前缀,可优化如下:

@Configuration
public 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
@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访问页面出现多余前缀和后缀情况

页面中出现hello.jsp

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

解决方法

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

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

关于“springboot怎么为web层添加统一请求前缀”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI