Springboot 使用过滤器匹配并删除多个前缀

例如:请求http://localhost/api/user 过滤之后请求 http://localhost/user

创建过滤器,代码如下

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(1)
@WebFilter(urlPatterns = {"/dss/*", "/api/*"})
public class RemovePrefixFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // Get the request URI
        String uri = httpRequest.getRequestURI();

        // 定义要删除的前缀数组,前缀不能相同
        String[] prefixesToRemove = {"/api", "/dss"};

        // 遍历前缀并将其从 URI 中删除
        for (String prefix : prefixesToRemove) {
            if (uri.startsWith(prefix)) {
                uri = uri.substring(prefix.length());
                break;
            }
        }

        // Create a new request with the modified URI
        HttpServletRequest modifiedRequest = new ModifyRequestURI(httpRequest, uri);

        // Continue the filter chain with the modified request
        chain.doFilter(modifiedRequest, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code (if needed)
    }

    @Override
    public void destroy() {
        // Cleanup code (if needed)
    }
}

在此示例中,我们迭代前缀数组以从请求 URI 中删除并使用修改后的 URI 创建新请求。
这是此类的一个简单示例:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class ModifyRequestURI extends HttpServletRequestWrapper {

    private String modifiedUri;

    public ModifyRequestURI(HttpServletRequest request, String modifiedUri) {
        super(request);
        this.modifiedUri = modifiedUri;
    }

    @Override
    public String getRequestURI() {
        return modifiedUri;
    }
}

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