iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot如何为web层添加统一请求前缀
  • 615
分享到

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

2024-04-02 19:04:59 615人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录如何为WEB层添加统一请求前缀配置文件方式实现WebmvcConfigurer接口spring web访问页面出现多余前缀和后缀情况页面中出现hello.jsp解决方法如何为we

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

配置文件方式

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

server.servlet.context-path=/api

实现WebMvcConfigurer接口

重写configurePathMatch()方法,代码:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {    
    
    @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 {    
    
    @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 {
    
    @AliasFor(annotation = RequestMapping.class)
    String name() default "";
 
    
    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};
 
    
    @AliasFor(annotation = RequestMapping.class)
    String[] path() default {};
}

使用:

@ApiRestController("/demo")
public class DemoController extends BaseController{
}

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

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

页面中出现hello.jsp

解决方法

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: springboot如何为web层添加统一请求前缀

本文链接: https://www.lsjlt.com/news/139591.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springboot如何为web层添加统一请求前缀
    目录如何为web层添加统一请求前缀配置文件方式实现WebMvcConfigurer接口spring web访问页面出现多余前缀和后缀情况页面中出现hello.jsp解决方法如何为we...
    99+
    2022-11-13
  • springboot怎么为web层添加统一请求前缀
    这篇文章主要介绍“springboot怎么为web层添加统一请求前缀”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么为web层添加统一请求前缀”文章能帮助大家解决问题。如何为w...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作