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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31876389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:43:39  来源:igfitidea点击:

How to serve static html content page in spring-boot

javaspringspring-mvcspring-boot

提问by membersound

I'm starting an embedded tomcat via spring-bootand want to serve a static index.htmlpage as part of a running application.

我正在通过以下方式启动嵌入式 tomcat,spring-boot并希望将静态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. Why?

结果:当我调用 时localhost:8080,我只看到“index”这个词,而不是我的 html 页面。为什么?

采纳答案by membersound

My fault: I had an additional class with @EnableWebMvcannotation. This somehow messed up the spring-boot autoconfiguration. I removed it and now it works returning index.html.

我的错:我有一个带@EnableWebMvc注释的额外类。这以某种方式弄乱了 spring-boot 自动配置。我删除了它,现在它可以返回了index.html

回答by Alexandru Dumitrescu

For me this worked, i am sure there is a better way ( like without .html ).

对我来说这行得通,我相信有更好的方法(比如没有 .html )。

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

回答by Ankit Rawat

You can use ModelAndViewin 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

回答by GvSharma

Thats because of @RestController annotation, just removing this annotation works for me.

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