I
I
ilavio2021-02-10 11:49:35
Spring
ilavio, 2021-02-10 11:49:35

How to insert images into html views and configure Thymeleaf?

Hello! I can't deal with spring application. How to embed images in html correctly. The Thymeleaf docs say the following about the addResourceHandlers method: Add a resource handler for serving static resources based on the specified URL path patterns. The handler will be invoked for every incoming request that matches to one of the specified path patterns.

Patterns like "/static/**" or "/css/{filename:\\w+\\.css}" are allowed. See AntPathMatcher for more details on the syntax.

Returns:
a ResourceHandlerRegistration to use to further configure the registered resource handler

What's in translation: Add a resource handler to serve static resources based on the specified URL path patterns. The handler will be called for every incoming request that matches one of the specified path patterns.

Patterns such as "/static/**" or "/css/{filename:\\w+\\.css}" are allowed. See AntPathMatcher for more information about the syntax.

Return:
ResourceHandlerRegistration to further customize the registered resource handler.

But this doesn't explain anything to me: 1) where to locate this static folder? after webapp or java folder, main?
2) how to correctly specify a link to an image in html in a tag?
3) Considering examples of methods for specifying paths .addResourceHandler("/resources/**")
.addResourceLocations("/resources/static/img/"); In general, the brain is spinning. Trying to find a folder in the path of someone else's project, but it's not there. Then where did you get this path from?
And all the examples have cut paths (not from the beginning of the root folder) in order to understand where exactly you need to create these resource packs?

package www.ilil.com.config;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Configuration
@ComponentScan("www.ilil.com")// пакет для сканирования классов
@EnableWebMvc  // заменяет тег <mvc:annotation-driven/> и подлючает WEB функции
public class ApplicationContext1 implements WebMvcConfigurer {
  
  private final ApplicationContext applicationContext;

    @Autowired
    public ApplicationContext1 (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }
    
    public void configureViewResolvers (ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setCharacterEncoding("UTF-8");
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }

    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/spring-web-app2/src/main/resources/static/img/");
    }
    
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      configurer.enable();
  }
    

}


<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Красотка здесь</title>
<style>
</style>

</head>
<body>
  <h1>Крастока ЗДЕСЬ</h1>
  <img th:src="@{img/myImage.jpg}" width="300" height="200" alt="Штучка">


</body>
</html>


6023a0f762a70094156552.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ilavio, 2021-02-11
@ilavio

Thank you all! I managed to solve this problem. In the html itself I have specified:

<img th:src="@{/img/girl1.jpg}" width="300" height="200" alt="Штучка"/>

When setting up Thymeleaf in the addResourceHandlers method, I wrote the following:
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        
        registry
                .addResourceHandler("/img/**")
                .addResourceLocations("classpath:/static/img/");
    }

I also found out that if you have a lot of sources with folders, then you can specify the list separated by commas.
How can we make a conclusion in the 1st method, we specify the folder where the picture is located, and in the 2nd method, we indicate the previous folder of the folder where the picture is located.
My resources folder is nested in the main folder at the level with the java folder, as in the box in the question itself.
And thanks to Source: similar question

O
Orkhan Hasanli, 2021-02-10
@azerphoenix

Good afternoon!
Project images must be added to the resources/static directory. You can create the images directory and, accordingly, the path will be /resources/static/images
. And all subsequent uploaded files through the front can be stored either on distributed file systems or somewhere on the hosting.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question