3

I want to develop web app with spring boot and i want to address my javascript and css resources in jsp files. i config my access to this files from jsp in dispatcher-servlet.xml like this:

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

and in my jsp file i can use below code to access that:

<%@ 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">

how i do config mvc:resources mapping in spring boot?

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
behnam27
  • 241
  • 2
  • 4
  • 11

1 Answers1

11

Take a look at the 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.

Also you can use Java config that is the same as the xml that you posted. Just override the addResourceHandlers method of @Configuration class that extends WebMvcConfigurerAdapter

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

A good blog post about Spring resources - here.

Update:

  1. Note that for Spring boot 2.0.5 or later, WebMvcConfigurerAdapter has been deprecated. Instead we can implements WebMvcConfigurer.

  2. Note that for windows, we should pass string param to the addResourceLocations method like this: .addResourceLocations("file:///D:/beijing_pic_sample/")

  3. A related thread can be found here: How do I use Spring Boot to serve static content located in Dropbox folder?

Community
  • 1
  • 1
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • So do I need to `@Configuration` my DemoApplication class which is generated by the Spring boot framework, and then make it extending the `WebMvcConfigurerAdapter` by overriding the `addResourceHandlers` method? – ZhaoGang Nov 02 '18 at 07:42
  • 1
    @ZhaoGang I would suggest to create another Class in the same package as DemoApplication, e.g. `WebConfig` that is annotated with `@Configuration`, extends `WebMvcConfigurerAdapter`, etc. Your `DemoApplication` is annotated with `@SpringBootApplication` which extends `@Configuration`, so you can reuse that class as well, but in future you may have to add other configs that extend other Configurer Adapters... – Evgeni Dimitrov Nov 02 '18 at 08:45