0

I have the following structure

The dependencies i use:

  • spring-boot-starter
  • spring-boot-starter-test
  • spring-boot-starter-web
  • spring-boot-starter-thymeleaf
  • spring-boot-starter-security
  • thymeleaf-extras-springsecurity5
  • mysql-connector-java
  • spring-boot-starter-data-jpa
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/icon/**").addResourceLocations("classpath:/static/img/icon/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }

}

I have tried these in index.html

<img src="icon/signin.svg">
<img src="/icon/signin.svg">
<img src="./icon/signin.svg">
<img src="../static/img/icon/signin.svg">

unsuccesfully. In addition i tried to move resources directory to main directory, nothing. Any idea?

gaborbozo
  • 7
  • 5

3 Answers3

1

When you add @EnableWebMvc you override all auto configuration by SpringBoot. This should work:

@Configuration
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/icon/**").addResourceLocations("classpath:/static/img/icon/");
    }
}

Also I just had a look at the picture of your directory structure and I am certain unless my eyes are off is that your "resources" folder is not under src/main. It should be right beside the java folder:

src
|_ main
      |_ java
      |_ resources
Strelok
  • 50,229
  • 9
  • 102
  • 115
0

You can try how to serve static content in springboot 2.2.6? for the answer and links to other answers to the same rephrased question. And since you are using Spring Security you may want to look at your security configuration since starting from spring boot 2.0 static resources are secured by default https://spring.io/blog/2017/09/15/security-changes-in-spring-boot-2-0-m4

0

It turned out why it wasn't good for me. From Spring Boot 2.0 if you are using the @EnableWebSecurity you have to define manually which directories and files can be reached and by who

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
             .antMatchers("/**").permitAll() 
      ...
    }
...
}

In this case I let everyone to reach everything inside static folder.After this I can get the signin.svg in two ways:

<img src="icon/signin.svg"> <!--Because of registry.addResourceHandler("/icon/**").addResourceLocations("classpath:/static/img/icon/"); mapping -->
<img src="img/icon/signin.svg">
gaborbozo
  • 7
  • 5