Najoua Najoua - 6 months ago 25
Java Question

Can't display image on jsp page

I am trying to display an image on a jsp page.
I am developping using spring security/mvc.

Here's the folder structure
this is the part of jsp page :

<a href="/images/logo.png">
<img src="/images/logo.png" alt="logo">
</a>


and this is the configuration :

@Configuration
@EnableWebMvc
@ComponentScan(basePackages ="...")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {

@Bean(name="HelloWorld")
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");

return viewResolver;
}

/*
* Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
*
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");

}


@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

}


when I run the image doesn't display.
I tried a lot of suggestions none of them worked, I also tried relative and absolute paths.

Answer

Surely the problem is your file structure. Open the developer tools using CTRL+SHIFT+I (in Mozilla or Chrome) and inspect the image element. Surely the link is broken meaning that you are trying to source the images from the wrong location (or a non-existing one).

Use the context path:

<img src="${pageContext.request.contextPath}/images/logo.png"/> 
Comments