如何从 Spring Boot 提供静态 html? [英] How can I serve static html from spring boot?

查看:42
本文介绍了如何从 Spring Boot 提供静态 html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 运行 spring-boot-sample-web-static 项目在这里,对pom做了这个改动

I ran the spring-boot-sample-web-static project from here, made this alteration to the pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

并添加此类以从相同的 static 文件夹位置提供重复的页面 index2.html:

And added this class to serve a duplicate page index2.html from the same static folder location:

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Rester {

    @RequestMapping(value = "/rand", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    private RandomObj jsonEndpoint() {
        return new RandomObj();
    }

    @RequestMapping(value = "/tw")
    public String somePg() {
        return "index2";
    }
}

json url 工作正常,但是当我尝试访问 localhost:8080/tw 时,我得到一个空白页面,并且控制台中出现此错误:

The json url works fine, but when I try to access localhost:8080/tw I get a blank page, and this error in the console:

2017-02-22 15:37:22.076 ERROR 21494 --- [nio-8080-exec-9] o.s.boot.web.support.ErrorPageFilter     : Cannot forward to error page for request [/tw] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

我做错了吗?

推荐答案

静态文件应该来自资源,而不是来自控制器.

Static files should be served from resources, not from controller.

Spring Boot 会自动添加位于以下任一目录:

Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/  
/resources/  
/static/  
/public/

参考:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/

这篇关于如何从 Spring Boot 提供静态 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆