【问题标题】:Why can't this Spring Boot application find the main page?为什么这个 Spring Boot 应用程序找不到主页?
【发布时间】:2018-01-15 04:30:09
【问题描述】:

我正在尝试创建一个允许我使用的最小 Spring Boot 应用程序 前端的 ReactJS。

我想要达到的目标

当我运行 Spring Boot 应用程序时,它应该显示一个带有 React 的页面 里面的组件。

项目结构

你可以找到源代码here。

我得到了什么

当我

  1. 运行mvn cleanmvn clean spring-boot:run` 和
  2. 导航到http://localhost:8080,

我收到 404 错误(见下文)。

我该如何解决?

注意事项:

  1. 我复制了教程React.js and Spring Data REST中的方法。
  2. 不要告诉我摆脱 Kotlin,它不太可能是 Kotlin 导致问题。

更新 1(07.08.2017 22:17 MSK):

mvn clean spring-boot:run的输出可以找到here。

更新 2(07.08.2017 22:44 MSK):

在MyApp 类中将RestController 更改为Controller 并移动main 它里面的方法没有帮助。

目前,MyApp 类如下所示:

@SpringBootApplication
@Controller
open class MyApp {
    fun main(args: Array<String>) {
        SpringApplication.run(MyApp::class.java,*args)
    }
}

【问题讨论】:

  • 您在控制台(您输入mvn 命令的位置)上看到了哪些消息?您是否看到“服务器已启动”等?
  • 广告您是否看到“服务器已启动”等?:是的。我在更新 1 中包含了 mvn clean spring-boot:run 的输出。
  • 请不要链接您的错误和输出。将它们复制到此处并正确格式化,这样链接以后就不会更改或过期。

标签: java maven reactjs spring-boot kotlin


【解决方案1】:

现在我没有使用 Kotlin 的经验,但我可以告诉您,您在以下代码中遗漏了一些东西(除了有一个额外的 RestController 注释)。

@SpringBootApplication
@RestController
open class MyApp {

}

在 Java 中,该类实现了 ServletContextInitializer,并在其中使用以下静态方法运行 main:

SpringApplication.run(MyApp.class, args);

我希望这会有所帮助。

更新

尝试同时添加一个模板解析 bean,现在这不是唯一的方法,但值得一试,如下所示:

@Bean
public ClassLoaderTemplateResolver yourTemplateResolver() {
    ClassLoaderTemplateResolver yourTemplateResolver = new ClassLoaderTemplateResolver();
    yourTemplateResolver.setPrefix("templates/");
   return yourTemplateResolver;
}

并将以下行添加到您的 application.properties:

spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html

别忘了将百里香导入你的 POM:

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

【讨论】:

  • 他正在等待一个页面。所以@RestController 在这个用例中不是正确的注释。应该改用@Controller。
  • 实际上在控制器中他使用了controller 注释,请参见此处:github.com/dpisarenko/minimal-react-boot-project/blob/master/… 但在应用程序初始化程序和 RestController 中......
  • 感谢您的回答。我试过了,但没有帮助(见更新 2)。
  • 您能否尝试添加ClassLoaderTemplateResolver bean,尽管它来自Thymeleaf,但由于您将模板添加到sources 文件夹,我假设您需要添加模板解析器。检查答案的更新。
  • 有点晚了 :) 现在检查一下。
猜你喜欢
  • 2019-05-06
  • 2020-05-14
  • 2015-04-11
  • 2017-01-09
  • 1970-01-01
  • 2017-03-27
  • 2019-12-31
  • 2018-01-10
  • 2019-01-25
相关资源
最近更新 更多