【问题标题】:Spring does not show home.htmlSpring 不显示 home.html
【发布时间】:2019-11-04 20:56:03
【问题描述】:

我正在学习 Spring 框架。我在resources/templates/home.html 中添加了home.html。但是当我访问http://localhost:8080 时它是不可见的。我有以下结构:

taco-cloud\src\main\java\tacos\TacoCloudApplication.java

package tacos;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TacoCloudApplication {

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

}

taco-cloud\src\main\java\tacos\HomeController.java

package tacos;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController 
{
    @GetMapping("/")
    public String home()
    {
        return "home.html";
    }
}

taco-cloud\src\main\resources\static\home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:th="http://www.thymeleaf.org">
 <head>
 <title>Taco Cloud</title>
 </head>
 <body>
 <h1>Welcome to...</h1>
 <img th:src="@{/images/TacoCloud.png}"/>
 </body>
</html>

输出

可白化的错误页面

localhost:8080/home.html 显示主页.html

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    您必须将主页的位置更改为在static 文件夹中:

    resources/static/home.html
              ^^^^^^
    

    而不是

    resources/templates/home.html
    

    并在您的控制器中指定扩展名:

    return "home.html";
                ^^^^^
    

    否则您必须创建视图解析器以避免使用扩展程序并指定页面的其他位置,请查看 Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error

    【讨论】:

    • 它没有用。我都按照你的建议做了。我已经编辑了我的问题。但是 localhost:8080/home.html 正在工作。但是 localhost:8080 应该显示 home.html @YCF_L
    • 尝试在控制器类的 return 语句中删除 .html 扩展名
    • 我确实删除了 .html 扩展名,但它不起作用。 @m-2127
    • @Aman 它非常适合我,你确定你遵循了正确的步骤吗?
    • localhost:8080/home.html 显示 home.html @YCF_L
    【解决方案2】:

    你可以试试这个。

    @GetMapping("/")
        public String home()
        {
            return "templates/home.html";
        }
    

    Check more details

    【讨论】:

    • 添加你的文件位置“static/home.html”
    • 这是我的问题@BipilRaut
    • 你有扩展@Configuration public class MvcConfig extends WebMvcConfigurerAdapter{}
    • 没有。我没有@BipilRaut
    • 我在 pom.xml 文件中看到您的项目有任何错误,请您清理安装您的 pom 文件
    【解决方案3】:

    以下是您可以在项目中放置 html 文件的几种不同方式。(注意它的优先级从高到低) src/main/resources/resources/home.html src/main/resources/static/home.html src/main/resources/public/home.html

    通过this了解spring mvc项目结构

    【讨论】:

      猜你喜欢
      • 2022-09-26
      • 2019-02-14
      • 2019-06-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2021-10-12
      相关资源
      最近更新 更多