Problems with image localization in the Spring Framework

Asked

Viewed 543 times

2

I’m using Spring and Thymeleaf:

I have an image in the directory:

Resources/image/Telescope.png

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

http://localhost:8080/Search services/

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

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

But when I click on a link from the home page 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 page posts.html again ,I can no longer load the image what is happening?

In inspecting it says it can not carry the image src that is mounted so by Spring:

http://localhost:8080/Search services/category/Resources/image/Telescope.png

The image really isn’t at this address! She is still here:

Resources/image/Telescope.png

I don’t understand why he created this concatenation for the image src!

In the configuration class I enabled everything on the Resources page to be loaded:

public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
...
...
  • You passed a relative address, so he "agreed," if you put a / at the image address, the behavior will not be that

  • What do you use in the View? html only?

  • 1

    If you use Thymeleaf you can do so: <img th:src="@{/resources/imagem/telescope.png}">

  • 1

    @Denisrudneidesouza Thanks! That’s right, I forgot to mention I was wearing Hymeleaf!!! It’s been a while since I worked with Thymeleaf!! It was shot and fall!!

1 answer

1


This problem occurs because it is informing the relative path of the image, so the system will use as a basis the current url and add to it.

To use the absolute path, you must use the url with a slash at the beginning.

Using the absolute path can cause future problems, for example: if the context of the application changes, the absolute address will no longer be valid, so Thymeleaf has a special syntax to be able to enter 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, the @{} will take the context (BuscaServicos) and add before the url

Browser other questions tagged

You are not signed in. Login or sign up in order to post.