如何更改Spring Boot服务静态文件的方式? [英] How to change the way Spring Boot serves static files?

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

问题描述

最近在几个新项目上使用了JHipster(强烈建议!惊人的工作!)之后,我试图将某些概念回移植到一个较旧的Webapp中,实质上是将其迁移到Spring Boot和Angular.

After using JHipster on a couple of new projects recently (Highly recommended ! Amazing work !), I am trying to back-port some of the concepts into an older webapp, essentially migrating it to Spring Boot and Angular.

在Spring Boot中,静态Web资源(HTML,JS,CSS等)的默认位置位于名为publicstaticresources的目录中,该目录位于类路径的根目录下.这些目录中的任何一个都将在春季启动时被选中,并且其中的文件可以通过HTTP访问.

In Spring Boot, the default location for static web resources (HTML, JS, CSS, etc.) is in a directory called public, static or resources located at the root of the classpath. Any of these directories will be picked up by spring boot and files in them will be accessible via HTTP.

在JHipster中,Web文件位于src/main/webapp目录中.经典Maven WAR项目中默认使用的目录.

In JHipster the web files are in the src/main/webapp directory. Which is the directory used by default in a classic Maven WAR project.

我更喜欢这样做是因为:

I like this better because :

  • 更清楚地将静态Web内容与Java代码使用的类路径资源分开
  • 嵌套的深度较小(我们已经有足够多的目录嵌套到Maven中了!)

但是,如果我只是在项目中创建webapp目录并将HTML文件放入其中,则它们无法通过HTTP使用,并且构建过程会在其中创建WEB-INF目录结构.我不想要,在JHipster中不是这样.

But if I just create webapp directory in my project and put my HTML files in it, they are not available via HTTP, and the build process creates the WEB-INF directory structure in it. I don't want that, and in JHipster this is not the case.

如何配置Spring Boot以使其表现与JHipster一样?

对于不熟悉JHipster的用户:如何指示Spring Boot从其他文件夹(不包含在类路径中)提供静态文件?

For those not familiar with JHipster : How can I instruct Spring Boot to serve static files from a different folder, no included in the classpath ?

推荐答案

您可以尝试以下配置.这个想法应该很简单.它确实在assets目录中注册了工件.

You can try following configuration. The idea should be pretty straight forward. It does register artifacts in assets directory.

public class AppMvcConfiguration extends WebMvcConfigurerAdapter {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      // Including all static resources.

      registry.addResourceHandler("/assets/**", 
                  "/css/**", 
                  "/img/**",
                  "/js/**"
             ).addResourceLocations("/assets/",
                  "/css/", 
                  "/img/",
                  "/js/"
      ).resourceChain(true)
       .addResolver(new PathResourceResolver());

       super.addResourceHandlers(registry);
  }
}

这篇关于如何更改Spring Boot服务静态文件的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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