Problems with image localization in Spring Framework

2

I'm using Spring and Thymeleaf:

I have an image in the directory:

  

resources / image / telescope.png

When I open the posts.html (home) page, located at the address below, the image is displayed.

  

link

Code to call the image in posts.html (home):

<img src="resources/imagem/telescope.png">

But when I click on a home page link to call a service in the HomeController:

@RequestMapping(value = "/categoria/{link}", method = RequestMethod.GET)
public ModelAndView postByCategoria(@PathVariable("link") String link, ModelMap model) {

    List<Postagem> postagems = postagemService.findByCategoria(link);
    model.addAttribute("postagens", postagems);
    return new ModelAndView("posts.html", model);
}

The above method returns a view to the posts.html page again, I can not load the image anymore what's happening?

On inspecting it it says that it can not load the src of the image that is mounted by Spring:

  

link

The image is not really at this address! It's still here:

  

resources / image / telescope.png

I do not understand why he created this concatenation for the src of the image!

In the configuration class I enabled everything on the resources page to load:

public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
...
...
    
asked by anonymous 05.07.2017 / 19:10

1 answer

1

This problem occurs because you are reporting the relative path of the image, so the system will use the current url as the base and add the one you entered.

In order to use the absolute path, you must use the url with a slash at the beginning.

Using the absolute path can cause you future problems, for example: if the application context changes, the absolute address will no longer be valid, so thymeleaf has a special syntax for entering addresses, in your case it would look like this:

 <img th:src="@{/resources/imagem/telescope.png}">

Note the bar at the beginning of the url indicating that the path is absolute, also note that I used @{endereço} next to th:src , @{} will get the context (BuscaServicos) and add before url

    
05.07.2017 / 20:24