spring boot 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() {

    }
}

你可能感兴趣的:(spring,boot)