spring - 如何在spring boot中配置Spring mvc静态资源映射配置:<mvc:resources mapping. ../>?

标签 spring spring-mvc spring-boot

我想用 spring boot 开发 web 应用程序,我想在 jsp 文件中解决我的 javascript 和 css 资源。
我在 dispatcher-servlet.xml 中从 jsp 配置我对这个文件的访问,如下所示:

<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

在我的 jsp 文件中,我可以使用下面的代码来访问它:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
 <img class="first-slide home-image" src="<spring:url value="/resources/images/back1.jpg"/>" alt="First slide">

我如何在 Spring Boot 中配置 mvc:resources 映射?

最佳答案

看看docs .

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.


您也可以使用与您发布的 xml 相同的 Java 配置。只需覆盖 addResourceHandlers @Configuration的方法扩展 WebMvcConfigurerAdapter 的类
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
一篇关于 Spring 资源的好博文 - here .
更新:
  • 请注意,对于 Spring boot 2.0.5 或更高版本,WebMvcConfigurerAdapter已被弃用。相反,我们可以 implements WebMvcConfigurer .
  • 请注意,对于 Windows,我们应该将字符串参数传递给 addResourceLocations像这样的方法:.addResourceLocations("file:///D:/beijing_pic_sample/")
  • 可以在此处找到相关主题:How do I use Spring Boot to serve static content located in Dropbox folder?
  • 关于spring - 如何在spring boot中配置Spring mvc静态资源映射配置:<mvc:resources mapping. ../>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40939802/

    相关文章:

    java - 将 daos Autowiring 到服务中,并将该服务 Autowiring 到 Junit 测试类中

    spring - 如何将 Keycloak 与 Spring 集成(无引导)?

    java - 部署 Spring 应用程序时出现 NullPointerException

    java - Spring Neo4j JPA native 动态排序查询

    java - 始终通过上下文在 Spring 服务中注入(inject)一些字段

    Spring Boot 模板未解决

    java - 如何在 jackson/Spring boot 中允许不区分大小写的枚举映射?

    spring-mvc - Spring 启动 : Log all incoming HTTP requests when using an embedded Jetty server?

    java - JPA 软删除存储库 + 审核

    java - SpringMVC批量加载资源文件(JS和CSS)