问题描述:
在运行springboot的时候访问 接口显示错误:
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 16 00:20:17 CST 2023 There was an unexpected error (type=Not Found, status=404).
问题解决:
分析:出现这种错误是因为你的路径找不到导致的
尝试解决:
-
查看路径是否正确(要与添加的一模一样)
确定路径没有错误那么就可能是路径没有添加上去
-
路径未添加/添加失败
为什么添加不上去
搜索代码一圈发现代码没有任何问题或者错误,一般也不是代码的问题,如果代码有问题就直接过不了编译,更别说跑起来还给你一个404错误
多半是文件位置的问题
你的接口类一定要在控制器类与启动类(带有@SpringBootApplication注解的类)的同包或者是子包下才可以被自动解析,否则就无法自动解析.
简单来说就是你的接口不能定义到装main函数的类的文件夹外部,否则你的接口无效.(不会报代码错误)
就像我把接口的定义到控制器类与启动类(带有@SpringBootApplication注解的类)的文件夹的外面去了,不报任何错误,接口就是访问不了,
-
添加路径输出函数
我们可以定义一个获取就看路径的类,调用这个类就可以获取所有开启的接口路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping;
import org.springframework.boot.actuate.endpoint.web.servlet.EndpointPathResolver;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class EndpointInfo {
private final AbstractWebMvcEndpointHandlerMapping endpointHandlerMapping;
@Autowired
public EndpointInfo(List<AbstractWebMvcEndpointHandlerMapping> handlerMappings) {
this.endpointHandlerMapping = getWebMvcEndpointHandlerMapping(handlerMappings);
}
public List<String> getAllEndpointPaths() {
List<String> endpointPaths = new ArrayList<>();
Map<RequestMappingInfo, HandlerMethod> handlerMethods = endpointHandlerMapping.getHandlerMethods();
for (RequestMappingInfo mappingInfo : handlerMethods.keySet()) {
Set<String> patterns = mappingInfo.getPatternsCondition().getPatterns();
endpointPaths.addAll(patterns);
}
return endpointPaths;
}
private AbstractWebMvcEndpointHandlerMapping getWebMvcEndpointHandlerMapping(
List<AbstractWebMvcEndpointHandlerMapping> handlerMappings) {
for (AbstractWebMvcEndpointHandlerMapping handlerMapping : handlerMappings) {
if (handlerMapping instanceof WebMvcEndpointHandlerMapping ||
handlerMapping.getClass().getName().equals("org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping")) {
return handlerMapping;
}
}
throw new IllegalStateException("No WebMvcEndpointHandlerMapping found");
}
}
我们注入了AbstractWebMvcEndpointHandlerMapping的实例,通过查找具体的WebMvcEndpointHandlerMapping实现类来获取。然后,我们遍历每个请求映射信息,并从中提取请求路径。最后,我们将所有的请求路径添加到一个列表中并返回。
请确保您的项目中已添加Actuator依赖项,并且已在类或配置中启用了Spring Boot Actuator,以便正确加载和使用Actuator模块。
本文由 mdnice 多平台发布