访问静态资源Spring MVC 4

时间:2017-05-18 19:10:06

标签: java spring-mvc java-ee

我已将Spring MVC设置如下,但未显示logo.png图像。我使用的是Spring 4.2.0.RELEASE

Image logo.png位于src / main / resources / images / logo.png

AppWebConfiguration.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="br.com.casadocodigo.loja")
public class AppWebConfiguration extends WebMvcConfigurerAdapter {

@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Bean(name="messageSource")
public MessageSource messageResource() {
    ReloadableResourceBundleMessageSource bundle = 
            new ReloadableResourceBundleMessageSource();
    bundle.setBasename("WEB-INF/messages");
    bundle.setDefaultEncoding("UTF-8");
    bundle.setCacheSeconds(1);
    return bundle;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/images")
        .setCachePeriod(3600)
        .resourceChain(true)
        .addResolver(new PathResourceResolver());   
}

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

}

ServletSpringMVC.java

public class ServletSpringMVC extends 
AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[] {AppWebConfiguration.class, JPAConfiguration.class};
}

@Override
protected String[] getServletMappings() {
    return new String[] {"/"};
}

}

JSP页面:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div>
    <img src="${pageContext.request.contextPath}/resources/images/logo.png" 
alt=""/>
</div>

1 个答案:

答案 0 :(得分:0)

试试这段代码,

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