Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

java - HandlerInterceptor spring - exclude requests on management port

I would like my HandlerInterceptor, in my spring boot application, not to run on requests coming in on the management port.

management.port = 9091

I can think of 2 ways to do it, but i'm looking for a more standard way.

One will be to check the port from within the HandlerInterceptor:

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        if(request.getLocalPort() == managementPort){
           return true;
        }
        else{
             ....
        }
}

The second will be to exclude all paths, related to the managementPort when registering the interceptor:

@Override
public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).excludePathPatterns(managementPortEndpoints);
}

This can easily get out of sync.

Is there a more native way to achieve it? (spring configuration of some sort)

question from:https://stackoverflow.com/questions/66053501/handlerinterceptor-spring-exclude-requests-on-management-port

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I choose javax.servlet.Filter for filtering requests.

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class BlockFilter implements Filter {
    private int managementPort = 9091;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request.getRemotePort() == managementPort) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).setStatus(401);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...