【问题标题】:Unable to make Spring MVC work无法使 Spring MVC 工作
【发布时间】:2018-08-02 19:16:26
【问题描述】:

我正在使用 Spring MVC 并试图了解控制器/视图部分的工作原理,但我在“/”和我尝试的任何其他路由上都收到 404 错误。 我尝试将@EnableWebMVC 添加到我的主类中,但这给了我一个500 错误Could not resolve view with name 'index' in servlet with name 'dispatcherServlet' 和一个异常,如下所列。

我的控制器:

public class MyController {
    @RequestMapping("/")
    public String index(Model model) {
        return "index";
    }
}

我有两个 /src/main/resources/static/index.html /.../resources/templates/index.html ,因为我还是 Spring/Thymeleaf 的新手,我不确定哪个应该工作

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'] with root cause

javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'

【问题讨论】:

    标签: java spring model-view-controller thymeleaf


    【解决方案1】:

    您不需要/src/main/resources/static/index.html 文件,因为它只是您的应用程序的静态页面。

    为了在调用控制器时动态生成页面,您需要一个模板,该模板应位于/src/main/resources/templates

    此外,您需要一个视图解析机制才能让 Spring MVC 正常工作,因为如果您在控制器方法中返回视图名称“index”,Spring 必须能够找出该怎么做。框架必须以某种方式“知道”这应该使用适当的模板引擎来触发模板src/main/resources/templates/index.html 的呈现,例如百里香叶。详情见这里:https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc-viewresolver

    如果您想使用 Thymeleaf,请参阅本教程了解如何将其配置为 Spring MVC 的模板引擎:http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

    提示:如果您使用的是 Spring Boot,只要将这两个依赖项添加到您的应用程序中,这都可以使用自动配置来实现:

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

    【讨论】:

    • 谢谢,我错过了 Thymeleaf 依赖项!我可以发誓我仔细检查了教程中的pom.xml 文件
    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 2012-09-03
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    相关资源
    最近更新 更多