Spring MVC show image

时间:2017-10-12 10:21:20

标签: spring-mvc

I want to show image in my JSP page in my Spring MVC Project , but the images are not working.

The images are located in src/main/webapp/resources/images folder

Folder structure

Please find the code below. Any help will be appreciated:

@Configuration
@EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurationSupport {

// Resource reading from jsp

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

//Here I declare a mapping of src\main\webapp\resources folder and all its content to a resource location value /resources/
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");

}


// Property reading from jsp
@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("/WEB-INF/i18n/application");
    return messageSource;
}


// View Resolver
@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
    //internalResourceViewResolver.setViewClass(JstlView.class);
    internalResourceViewResolver.setPrefix("/");
    internalResourceViewResolver.setSuffix(".jsp");
    return internalResourceViewResolver;
}

}

In the jsp it is called as :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
</head>
<body>
<img src="<c:url value='/resources/images/abc.jpg' />" >
</body>
</html>

2 个答案:

答案 0 :(得分:0)

基于我们的文件夹结构资源映射已更改

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

 //Here I declare a mapping of src\main\webapp\resources folder and all its 
  content to a resource location value /resources/
   registry.addResourceHandler("/resources/**")
   .addResourceLocations("/resources/");

}

答案 1 :(得分:0)

ResourceResolvers 可以根据其路径路径解析资源。他们还可以根据内部资源路径解析面向外部的公共URL路径供客户端使用。

XML配置:

<mvc:resources mapping="/resources/**" location="/resources/"/>

注释配置:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

在jsp中使用:

<img src="/contextpath/resources/images/abc.jpg" >

项目中的资源文件夹结构:

TestProject
|
src
|
WebContent
         |
          resources
                  |
                   js/css/images