更改默认 URL 映射以在 Spring 引导中提供静态内容

Changing default URL mapping for Serving Static Content in Spring Boot

当我使用以下映射在我的应用程序中添加一个新的控制器(非 rest)后,我的静态资源就停止工作了

@RequestMapping(value = "/{postId}/{postUri:.+}", method = RequestMethod.GET)
public String viewPost(@ModelAttribute("model") ModelMap model, PathVariable("postId") String postId, PathVariable("postUri") String postUri) {
          // do something
}

调试后发现我新添加的controller方法开始获取静态资源,基本上已经优先于静态资源的默认映射

例如,对以下静态资源的请求到达我的控制器而不是静态资源处理程序。

http://localhost:7999/css/bootstrap-2a31dca112f26923b51676cb764c58d5.css

我正在使用 spring boot 1.4

有没有办法修改映射 URL 以提供默认静态内容,因为我不想修改我的控制器方法的 URL?

没问题。有一个 spring.mvc.static-path-pattern 可以用来覆盖它:

spring.mvc.static-path-pattern=/resources/**

会将 classpath:/static/css/foo.css 映射到 /resources/css/foo.css

(我在 a862b6d 中说得更清楚了)

话虽如此,我只能强烈建议您更改那里的路径。拥有一个捕获根上下文的路径变量 确实是 一个坏主意。

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content

默认情况下 Spring Boot 将从类路径中名为 /static(或 /public 或 /resources 或 /META-INF/resources)的目录或从Servlet上下文。它使用来自 Spring MVC 的 ResourceHttpRequestHandler,因此您可以通过添加自己的 WebMvcConfigurerAdapter 并覆盖 addResourceHandlers 方法来修改该行为。

在独立的 Web 应用程序中,容器中的默认 servlet 也被启用,并且作为后备,如果 Spring 决定不处理它,则从 ServletContext 的根提供内容。大多数时候这不会发生(除非你修改默认的 MVC 配置)因为 Spring 总是能够通过 DispatcherServlet 处理请求。

默认情况下,资源映射到 /** 但您可以通过 spring.mvc.static-path-pattern 对其进行调整。例如,将所有资源重定位到 /resources/** 可以实现如下:

spring.mvc.static-path-pattern=/resources/**

您还可以使用 spring.resources.static-locations 自定义静态资源位置(用目录位置列表替换默认值)。如果您这样做,默认的欢迎页面检测将切换到您的自定义位置,因此如果启动时您的任何位置中有 index.html,它将成为应用程序的主页。

除了上面的“标准”静态资源位置之外,还为 Webjars 内容做了一个特例。如果以 Webjars 格式打包,路径在 /webjars/** 中的任何资源都将从 jar 文件提供。

我不会使用@EnableWebMVC。这对我有用,spring 默认情况下启动服务服务器静态内容 localhost:8888/ 以及 localhost:8888/some/path/

@Configuration
public static class WebServerStaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/some/path/").setViewName("forward:/index.html");
    }
}

我在application.properties

中添加了spring.resources.static-location=file:../frontend/build

index.html 存在于 build 文件夹中

使用也可以加绝对路径

spring.resources.static-location=file:/User/XYZ/Desktop/frontend/build

对于没有控制器的页面:

@Controller
@RequestMapping("/feature")
public class DataTableController {

    // map /feature/* to /feature/*
    @RequestMapping(value="/{name}", method = RequestMethod.GET)
    public ModelAndView staticPage(@PathVariable String name){
        return new ModelAndView("feature/" + name);
    }

}

除了HTML之外的静态资源:

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

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