打印springboot中所有的url地址
场景
在springboot框架中写了一个controller接口,但在启动项目后,死活调用不到那个新写的接口,这时我就想将框架中已经加载到的url地址全打印出来,看下到底是框架没加载到,还是说出现了其他故障。
在Spring Boot中,收到一个请求后,匹配到对应的URL的过程主要涉及以下几个步骤:
- 接收请求:当Spring Boot应用程序接收到一个HTTP请求时,它首先会通过Spring的DispatcherServlet进行接收。DispatcherServlet是Spring MVC中的核心组件,负责请求的接收和响应。
- 请求映射:DispatcherServlet会根据请求的URL路径和HTTP方法将请求映射到相应的处理方法。在映射过程中,Spring Boot使用了一个叫做RequestMappingHandlerMapping的组件。这个组件会根据请求的URL路径和HTTP方法找到最匹配的处理方法。
- 找到处理方法:RequestMappingHandlerMapping会根据请求的URL路径和HTTP方法找到对应的处理方法。如果找到了多个匹配的处理方法,它会根据一定的优先级规则选择其中一个进行处理。
- 调用处理方法:一旦找到了对应的处理方法,DispatcherServlet就会将请求传递给该处理方法进行处理。处理方法通常是一个带有@RequestMapping注解的方法,它可以是单个请求映射或多个请求映射。
- 处理结果:处理方法执行完成后,会返回一个ModelAndView对象,该对象包含了响应的数据和视图信息。DispatcherServlet会根据返回的ModelAndView对象生成响应并返回给客户端。
实现步骤
- 从上面在Spring Boot中,收到一个请求后的步骤中可以了解到,我们能从RequestMappingHandlerMapping对象中拿到框架已经加载好的url路径
- 当框架加载完成后,就从RequestMappingHandlerMapping对象中读取所需数据,类的参考代码如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
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.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
@Component
public class StartupConfig implements CommandLineRunner {
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Override
public void run(String... args) throws Exception {
printRequestMappings();
}
/**
* 打印出项目中所有的url请求地址和方法的映射关系
*/
public void printRequestMappings() {
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
RequestMappingInfo info = entry.getKey();
HandlerMethod method = entry.getValue();
Method targetMethod = method.getMethod();
String urlPath = "";
if (info.getPathPatternsCondition() != null) {
Set<String> patternValues = info.getPathPatternsCondition().getPatternValues();
for (String pattern : patternValues) {
urlPath = pattern;
}
}
String httpMethod = "";
Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
for (RequestMethod requestMethod : methods) {
httpMethod = requestMethod.name();
}
System.out.println("URL Path: " + urlPath + ", HTTP Method: " + httpMethod + " (" + targetMethod.getName() + ")");
}
}
}