我是春季mvc的新手,我有一些问题:
1)我可以从jsp页面访问WEB-INF目录中的img,css和js吗?
文件夹结构是:
webapp - WEB-INF - css - js - img
2)我有WebMvcConfig类,扩展了WebMvcConfigurerAdapter:
@Configuration @EnableWebMvc @Import({BeanConfig.class, CacheConfig.class}) public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/resources/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/").setCachePeriod(31556926);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ControllerInterceptor());
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public ContentNegotiatingViewResolver getContentNegotiatingViewResolver() {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
ArrayList<View> defaultViews = new ArrayList<View>();
MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
jsonView.setPrefixJson(true);
defaultViews.add(new MappingJacksonJsonView());
resolver.setDefaultViews(defaultViews);
resolver.setOrder(1);
return resolver;
}
@Bean
public ControllerInterceptor getLoggingInterceptor() {
return new ControllerInterceptor();
}
}
我想访问文件夹:/ resources / css,/ resources / img和/ resources / js,
web.xml文件的一部分:
<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value> config.WebMvcConfig </param-value> </init-param> </servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
文件夹结构是:
webapp - WEB-INF - resources - css - js - img
但它不起作用
答案 0 :(得分:5)
是的,你可以这样做。
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
你有这个结构
webapp
- WEB-INF
- resources
- css
- somefile.css
- js
- img
您可以访问
中的资源localhost:8080/context/css/somefile.css
将从/resources/css/somefile.css
获取资源。对所有其他资源都这样做。