spring4静态资源获取
Spring4做项目时,发现图片等静态资源获取不到,网上查询结果几乎相同,就是修改spring-servlet.xml配置,试了之后发现问题并不能解决,最后查看spring文档中的HTTP caching support for static resources,在项目web包里添加一个WebConfig.java文件,问题成功解决。
以下是WebConfig.java代码。
package com.smart.web;//修改为自己的目录 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan("com.smart.web") //修改为自己的目录 public class WebConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/img/**") .addResourceLocations("/static/images/"); } }
以下贴出我的项目目录。
在jsp页面中如需访问图片,实例
<img src="img/65186-106.jpg" alt="第三张">。
图片获取成功,问题解决。