【问题标题】:Spring Boot - index.html not found by controllerSpring Boot - 控制器找不到 index.html
【发布时间】:2017-12-15 19:42:24
【问题描述】:

我使用 SpringBoot 1.5.9 并创建了src/main/resources/static/index.html:

<!DOCTYPE html><html><head><meta charset="utf-8"/>
<title>Home</title></head>
<body><h2>Hello World!!</h2></body>
</html>

我的简单控制器正在处理“/”并转发到 index.html:

@Controller
    public class MyController {
        @RequestMapping("/")
        public String home(Model model) {
            System.out.println("In MyController!!!");
            return "index";
    }}

但是,当我从以下位置运行我的主要方法后:

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

然后我将浏览器指向:http://localhost:8080/ 我正进入(状态: 白标错误页面-出现意外错误(type=Not Found, status=404)

但是,如果我尝试直接访问该页面 - 它工作正常: http://localhost:8080/index.html

根据 SpringBoot 文档,src/main/resources/static/ 下的静态内容应该被渲染。 如果我创建文件夹src/main/resources/templates/ 并将我的index.html 放在那里,并在我的 pom.xml 中包含 spring-boot-starter-thymeleaf 依赖项,那么一切正常。但是我很困惑为什么 src/main/resources/static/index.html 的这个基本渲染 不管用。任何帮助表示赞赏。

【问题讨论】:

  • 删除你的 MyController 类,没有它它应该可以工作

标签: spring-boot


【解决方案1】:

刚刚找到解决办法:控制器MyController应该指定文件扩展名:

return "index.html";

【讨论】:

  • 我发现让它在没有扩展的情况下工作的唯一方法是添加到 pom.xml thymeleaf 依赖项。如果你添加这个依赖,它可以在没有扩展的情况下工作。
【解决方案2】:

最好在 Spring Boot 配置中添加viewResolver

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/403").setViewName("403");
    }    


    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }    

}

【讨论】:

  • 他没有在任何地方提到jsp文件。他甚至提到了/index.html
  • 这是一个老问题,但考虑到他的问题,他似乎是 spring 的新手,所以我想与他分享,因为我确信他没有创建 spring boot 项目只是用于显示html 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2016-04-16
  • 1970-01-01
  • 2018-08-05
  • 2017-05-01
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多