简体   繁体   English

在 Spring Boot MVC 中为静态文件提供服务的 URL 路径的默认资源处理程序

[英]Default resource handler for an URL path serving a static file in Spring Boot MVC

I have a Spring Boot-based project (based on spring-boot-starter-parent and spring-boot-starter-web in which I want to both serve static content (built in another module, and copied into the project with maven-resources-plugin ).我有一个基于 Spring Boot 的项目(基于spring-boot-starter-parentspring-boot-starter-web ,我想在其中提供静态内容(内置在另一个模块中,并使用maven-resources-plugin复制到项目中) maven-resources-plugin )。

With the default configuration/conventions, it looks for static content in misc.使用默认配置/约定,它会在 misc 中查找静态内容。 places, like classpath:/static and classpath:/public , which is useful if the static content is to be served from the root URL, which for this project is not the case.位置,如classpath:/staticclasspath:/public ,如果要从根 URL 提供静态内容,这很有用,但对于本项目而言并非如此。

I want to serve it off /web/ which I have successfully done by deriving from WebMvcConfigurer (and annotated the class with @Configuration ) and overridden the public void addResourceHandlers(ResourceHandlerRegistry registry) method;我想通过从WebMvcConfigurer (并用@Configuration注释该类)并覆盖public void addResourceHandlers(ResourceHandlerRegistry registry)方法成功地完成/web/服务; registry.addResourceHandler("/web/**").addResourceLocations("classpath:/static/web/");

This works when explicitly referring to the file names in the /web/ -folder, but I can't figure out how I can emulate the "default document" behavior, eg index.html should be served for /web/ .这在显式引用/web/文件夹中的文件名时有效,但我无法弄清楚如何模拟“默认文档”行为,例如应该为/web/提供index.html If you drop off an index.html in one of the root directories for static content, it will be handled by the WelcomePageHandlerMapping .如果您将index.html放在静态内容的根目录之一中,它将由WelcomePageHandlerMapping处理。

Found the solution;找到解决办法; I also had to override the addViewControllers() to create an explicit mapping and fix the precedence:我还必须覆盖addViewControllers()以创建显式映射并修复优先级:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/web/").setViewName("index.html");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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