如何从 Spring Boot 提供静态 html?

新手上路,请多包涵

我从 这里 运行了 spring-boot-sample-web-static 项目,对 pom 进行了修改

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

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

 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 时,我得到一个空白页,并且控制台中出现此错误:

 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

难道我做错了什么?

原文由 osmingo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 597
2 个回答

In Spring boot, /META-INF/resources/ , /resources/ , static/ and public/ directories are available to serve static contents.

因此,您可以在 --- 目录下创建一个 static/public/ resources/ 目录,并将静态内容放在那里。它们可以通过以下方式访问: http://localhost:8080/your-file.ext 。 (假设 server.port 是 8080)

您可以在 application.properties 中使用 spring.resources.static-locations 自定义这些目录。

例如:

 spring.resources.static-locations=classpath:/custom/

现在您可以使用 custom/ 下的文件夹 resources/ 来提供静态文件。

这也可以在 Spring Boot 2 中使用 Java 配置:

 @Configuration
public class StaticConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
    }
}

此配置将 custom 目录的内容映射到 http://localhost:8080/static/** url。

原文由 Hamid Mohayeji 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题