Spring 问题:出现意外错误(类型=未找到,状态=404)

Posted

技术标签:

【中文标题】Spring 问题:出现意外错误(类型=未找到,状态=404)【英文标题】:Issue With Spring: There was an unexpected error (type=Not Found, status=404) 【发布时间】:2016-08-17 14:05:21 【问题描述】:

我正在阅读这本关于 Spring 的宁静 Web 服务的书。我决定放弃他们正在做的事情并使用 java 配置文件。出于某种原因,在切换到 Java 配置后,服务将正确运行(在控制台窗口中),但是当我实际转到 localhost 上的端点时,我得到了这个:

白标错误页面

这个应用程序没有明确的 /error 映射,所以你看到 这是一个后备。

2016 年 4 月 23 日星期六 20:48:25 PDT 出现意外错误(type=Not 找到,状态=404)。没有可用的消息

这是来自 GET 请求的响应:


    "timestamp": 1461470029110,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/greeting"

这个故事的下一章开始于我去 Spring 网站上的入门页面 http://spring.io/guides/gs/rest-service/ 我决定开始一个小项目来重新创建他们的基础教程。我将在下面发布我编写的代码供您查看。问题是,我遇到了完全相同的问题。服务运行,但我无法到达端点。我不确定发生了什么,我看到其他人有类似的问题,但答案并没有适用/帮助我。我确信很明显我做错了,任何帮助将不胜感激。最后一条信息,如果有关系的话,我使用 IntelliJ IDEA 15 CE 作为我的 IDE。

被击中的端点:

http://localhost:8080/greeting

我的控制器

@RestController
public class GreetingController 
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World")String name) 
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    

我的资源表示类

public class Greeting 
    private final long id;
    private final String content;

    public Greeting(long id, String content) 
        this.id = id;
        this.content = content;
    

    public long getId() 
        return id;
    

    public String getContent() 
        return content;
    

我的主要

@SpringBootApplication
public class Application

    public static void main(String[] args)
    
        SpringApplication.run(Application.class, args);
    

我的 POM 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.organization_name.webservices</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

命令行运行

mvn spring-boot:run   

来自控制台的完整日志

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.3.RELEASE)

2016-04-23 20:47:53.153  INFO 7898 --- [           main] c.t.webservices.application.Application  : Starting Application on Macintosh.local with PID 7898 (/Users/<my_user>/Downloads/B04788_Code/HelloWorld/target/classes started by <my_user> in /Users/<my_user>/Downloads/B04788_Code/HelloWorld)
2016-04-23 20:47:53.156  INFO 7898 --- [           main] c.t.webservices.application.Application  : No active profile set, falling back to default profiles: default
2016-04-23 20:47:53.242  INFO 7898 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@68ceda24: startup date [Sat Apr 23 20:47:53 PDT 2016]; root of context hierarchy
2016-04-23 20:47:54.084  INFO 7898 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-04-23 20:47:54.811  INFO 7898 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-04-23 20:47:54.840  INFO 7898 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-04-23 20:47:54.841  INFO 7898 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.32
2016-04-23 20:47:54.960  INFO 7898 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-04-23 20:47:54.960  INFO 7898 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1736 ms
2016-04-23 20:47:55.214  INFO 7898 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-04-23 20:47:55.218  INFO 7898 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-04-23 20:47:55.219  INFO 7898 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-04-23 20:47:55.219  INFO 7898 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-04-23 20:47:55.219  INFO 7898 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-04-23 20:47:55.545  INFO 7898 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@68ceda24: startup date [Sat Apr 23 20:47:53 PDT 2016]; root of context hierarchy
2016-04-23 20:47:55.605  INFO 7898 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error]" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-04-23 20:47:55.606  INFO 7898 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error],produces=[text/html]" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-04-23 20:47:55.628  INFO 7898 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-23 20:47:55.628  INFO 7898 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-23 20:47:55.657  INFO 7898 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-23 20:47:55.776  INFO 7898 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-04-23 20:47:55.848  INFO 7898 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-04-23 20:47:55.853  INFO 7898 --- [           main] c.t.webservices.application.Application  : Started Application in 3.531 seconds (JVM running for 4.702)
2016-04-23 20:48:19.521  INFO 7898 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-04-23 20:48:19.521  INFO 7898 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-23 20:48:19.533  INFO 7898 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms

GET 请求后更新控制台

2016-04-23 20:48:19.521  INFO 7898 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-23 20:48:19.533  INFO 7898 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms

停止后的控制台

2016-04-23 20:53:24.494  INFO 7898 --- [       Thread-2] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@68ceda24: startup date [Sat Apr 23 20:47:53 PDT 2016]; root of context hierarchy
2016-04-23 20:53:24.495  INFO 7898 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Process finished with exit code 130

再次感谢您提供的任何帮助。我会及时通知大家更新!

【问题讨论】:

为了清楚起见 - 当您转到 localhost:8080/greeting 或只是 localhost:8080 时,您会看到白标签错误页面?当我转到 localhost:8080 时,我看到了同样的结果,但是当我转到 /greeting 时它工作得很好。 好问题,我应该更清楚。是的,GET 是针对端点本身进行的,localhost:8080/greeting 我更新了问题以反映现在:) 【参考方案1】:

我相信您的问题与包裹有关。您的应用程序在com.organization_name.webservices.application 中定义。我猜你的其他类在一个不同的包中,它不是com.organization_name.webservices.application 的子包。 Spring 会自动加载同一个包或子包中的控制器,例如:

com.organization_name.webservices.application
com.organization_name.webservices.application.controllers

但不是这样的包:

com.organization_name.webservices.controllers

您可以通过移动控制器(或应用程序)或将 ComponentScan 添加到您的应用程序来解决此问题:

@SpringBootApplication
@ComponentScan(basePackageClasses=GreetingController.class)
public class Application 

您应该会在日志中看到这一点:

 Mapped "[/greeting]" onto public com.organization_name.webservices.xxx.Greeting com.organization_name.webservices.xxx.GreetingController.greeting(java.lang.String)

【讨论】:

必须额外添加:import org.springframework.context.annotation.ComponentScan;import main.java.hello.GreetingController; 如果您的请求映射没有被任何控制器处理,有时也会出现此错误。 谢谢,这真的很有帮助!【参考方案2】:

似乎您缺少 thymleaf 依赖项。把它放在你的 pom.xml 依赖项中

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

【讨论】:

完全正确。谢谢【参考方案3】:

在 pom.xml 中添加如下依赖

     <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

【讨论】:

【参考方案4】:
    Adding these dependencies helped me :

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>


@EnableSwagger2
@Configuration
public class swagger 
    public Docket productApi() 
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.Mongo"))
                .paths(regex("/mongo.*"))
                .build();
    

【讨论】:

【参考方案5】:

其实我也遇到了同样的错误。

根本原因是文件夹结构。

public static void main(String[] args)  

main 方法包含的类应该放在第一位。 之后只剩下剩下的类和包。

【讨论】:

该问题的答案与控制器未放入正确的包中且 Spring 未看到这一事实有关。您的回答与此无关。我没有投反对票。你应该删除这个答案。

以上是关于Spring 问题:出现意外错误(类型=未找到,状态=404)的主要内容,如果未能解决你的问题,请参考以下文章

Spring @RestController,spring-boot 出现意外错误(类型=不可接受,状态=406)

删除操作返回错误:出现意外错误(类型=禁止,状态=403)。禁止的

弹簧靴白标404

运行 Spring Boot 应用程序时出错

Spring Boot JSP 404:找不到页面

Spring Boot 可执行 jar 无法访问索引页面