java 如何在Sping Boot 应用程序启动后检索所有的请求方法,请求路径,请求头和请求体?

yxyvkwin  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(169)

我们希望在Sping Boot 应用程序启动后创建一个包含所有请求方法,路径,头部和主体的文件。我的意思是甚至在任何端点被击中之前。这能实现吗?下面的代码似乎不起作用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;
import java.util.Set;

@Component
public class EndpointScanner {

    private RequestMappingHandlerMapping handlerMapping;

    @Autowired
    public EndpointScanner(RequestMappingHandlerMapping handlerMapping) {
        this.handlerMapping = handlerMapping;
    }

    public void scanEndpointsWithRequestBody() {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();

        for (RequestMappingInfo requestMappingInfo : handlerMethods.keySet()) {
            HandlerMethod handlerMethod = handlerMethods.get(requestMappingInfo);
            Set<String> methods = requestMappingInfo.getMethodsCondition().getMethods();

            // Check if the endpoint accepts a request body
            if (methods.size() > 0 && handlerMethod.getMethod().getParameterCount() > 0) {
                RequestMapping requestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
                String[] paths = requestMapping.value();
                // You can also access other details like HTTP methods, headers, etc.

                for (String path : paths) {
                    System.out.println("Endpoint: " + path);
                }
            }
        }
    }
}
smdncfj3

smdncfj31#

要在Sping Boot 应用程序启动后检索所有请求方法,请求路径,请求头和请求体,您可以使用Servlet API提供的Filter接口的实现。下面是一个如何实现此目标的示例:
1.创建一个实现Filter接口的新类。这个类将拦截传入的HTTP请求并提取所需的信息。例如:

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

public class RequestLoggingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization logic, if any
    }

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

            // Retrieve the request method, path, headers, and body here
            String method = httpRequest.getMethod();
            String path = httpRequest.getRequestURI();
            String headers = httpRequest.getHeader("headerName"); // Replace "headerName" with the desired header name
            String body = httpRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

            // Perform logging or any other processing with the retrieved information
            System.out.println("Request Method: " + method);
            System.out.println("Request Path: " + path);
            System.out.println("Request Headers: " + headers);
            System.out.println("Request Body: " + body);
        }

        // Proceed with the request chain
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Cleanup logic, if any
    }
}

1.在Sping Boot 应用程序中注册RequestLoggingFilter。有几种方法可以做到这一点:
a.如果您使用Sping Boot 的默认嵌入式servlet容器(例如Tomcat),则可以将filter注册为@Configuration类中的bean:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public FilterRegistrationBean<RequestLoggingFilter> requestLoggingFilterRegistration() {
        FilterRegistrationBean<RequestLoggingFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RequestLoggingFilter());
        registration.addUrlPatterns("/*"); // Apply the filter to all URLs
        return registration;
    }
}

B.如果你使用Sping Boot 和Spring MVC,你可以通过扩展WebMvcConfigurerAdapter类来注册过滤器:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestLoggingFilter());
    }
}

1.启动Sping Boot 应用程序,RequestLoggingFilter将拦截所有传入的请求并记录请求的信息。
注意:确保将代码中的"headerName"替换为要检索的头的实际名称。此外,请记住,记录请求正文可能会涉及安全问题,因此请谨慎使用,并确保不会无意中记录敏感信息。

相关问题