简体   繁体   English

如何在 spring-boot 中提供静态 html 内容页面

[英]How to serve static html content page in spring-boot

I'm starting an embedded tomcat via spring-boot and want to serve a static index.html page as part of a running application.我正在通过spring-boot嵌入式 tomcat,并希望将静态index.html页面作为正在运行的应用程序的一部分提供服务。

But the following does not work:但以下不起作用:

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


@RestController 
public class HomeContoller {
    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

src/main/resources/static/index.html

Result: when I call localhost:8080 , I just see the word "index", but not my html page.结果:当我调用localhost:8080 ,我只看到“index”这个词,而不是我的 html 页面。 Why?为什么?

My fault: I had an additional class with @EnableWebMvc annotation.我的错:我有一个带有@EnableWebMvc注释的附加类。 This somehow messed up the spring-boot autoconfiguration.这以某种方式弄乱了 spring-boot 自动配置。 I removed it and now it works returning index.html .我删除了它,现在它可以返回index.html

For me this worked, i am sure there is a better way ( like without .html ).对我来说这行得通,我相信有更好的方法(比如没有 .html )。

@RequestMapping("/")
public String index() {
    return "index.html";
}

You can use ModelAndView in order to serve static HTML content in spring boot.您可以使用ModelAndView在 Spring Boot 中提供静态 HTML 内容。

@RequestMapping("/")
public ModelAndView home()
{
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("index");
    return modelAndView;
}

application.properties:- application.properties:-

spring.mvc.view.suffix = .html spring.mvc.view.suffix = .html

HTML File : - src/main/resources/static/index.html HTML 文件:- src/main/resources/static/index.html

那是因为@RestController 注释,删除这个注释对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM