简体   繁体   中英

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.

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?

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

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

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

You can use ModelAndView in order to serve static HTML content in spring boot.

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

application.properties:-

spring.mvc.view.suffix = .html

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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