当前位置:主页 > 软件编程 > JAVA代码 >

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

时间:2023-03-15 09:24:03 | 栏目:JAVA代码 | 点击:

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

您可能感兴趣的文章:

相关文章