Spring 3,具有基于Java的配置和资源访问问题
问题内容:
我正在使用带有BootStrap的Spring 3(基于Java的配置)。
我已经下载了引导程序并将css和js放在资源目录下。
我无法在freemarker页面中使用这些.css的问题。但是,我将它们导入了。当我使用基于Java的配置时,我添加了“
addResourceHandler”,如下所示:
WebAppConfig:
@Configuration
@EnableWebMvc
@ComponentScan("com.springway")
public class WebConfig implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setServletContext(servletContext);
root.scan("com.springway");
root.refresh();
final ServletRegistration.Dynamic servlet = servletContext.addServlet("spring", new DispatcherServlet(root));
servlet.setLoadOnStartup(1);
servlet.addMapping("/*");
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
Tomcat日志说:
“警告:找不到带有URI的HTTP请求的映射
[/springway/resources/css/bootstrap-sensitive.css]在DispatcherServlet中,名称为“
spring”
目录 :
-SpringWay
> -src
> - main
> -webapp
> -resources
-WEB-INF
-welcome.ftl
-springway.ftl
welcome.ftl:
[#ftl /]
[#include "springway.ftl" /]
<ul class="breadcrumb">
<li>
<a href="[@spring.url '/test'/]">Test</a> <span class="divider">/</span>
</li>
<li>
<a href="#">Library</a> <span class="divider">/</span>
</li>
<li class="active">Data</li>
</ul>
springway.ftl:
[#ftl/]
[#import "spring.ftl" as spring /]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
<link href="[@spring.url '/resources/css/bootstrap-responsive.css'/]" rel="stylesheet" type="text/css" media="screen"/>
<link href="[@spring.url '/resources/css/bootstrap-responsive.min.css'/]" rel="stylesheet" type="text/css" media="screen"/>
<link href="[@spring.url '/resources/css/bootstrap.css'/]" rel="stylesheet" type="text/css" media="screen"/>
<link href="[@spring.url '/resources/css/bootstrap.min.css'/]" rel="stylesheet" type="text/css" media="screen"/>
<script src="[@spring.url '/resources/js/bootstrap.js'/]" type="text/javascript"></script>
<script src="[@spring.url '/resources/js/bootstrap.min.js'/]" type="text/javascript"></script>
</head>
<body ></body>
</html>
问题答案:
您定义了错误的resourceLocation。
代替
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
你应该做的
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/**");
由于您的css文件夹位于资源文件夹内,因此您需要在/后面加上额外的**,之后才能识别css文件夹,否则仅从资源文件夹加载而不考虑子文件夹。
希望对您有所帮助。
干杯。