信息发布→ 登录 注册 退出

springboot controller 增加指定前缀的两种实现方法

发布时间:2026-01-11

点击量:
目录
  • controller 增加指定前缀
    • 1、增加配置
    • 2、过滤拦截
  • springboot服务端口、项目前缀的配置
    • 在application.properties中配置

controller 增加指定前缀

1、增加配置

server.servlet.context-path: /api

这种是最常见的,加上这个配置后,所有的url,必须带上/api的前缀,才能访问到该url

2、过滤拦截

这种是加上/api也可以访问,不加/api也可以访问,适合项目重构修改的适合用

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Configuration
@Order(1)
@WebFilter(filterName = "urlFilter", urlPatterns = "/api/*")
public class UrlFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String servletPath = httpRequest.getServletPath();
        if (StringUtils.isNotBlank(servletPath) && servletPath.startsWith("/api")) {
            String newPath = servletPath.substring(4);
            request.getRequestDispatcher(newPath).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }
    @Override
    public void destroy() {
    }
}

springboot服务端口、项目前缀的配置

在application.properties中配置

server.port: 8081
server.context-path: /demo

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

在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!