【发布时间】:2015-05-24 05:18:49
【问题描述】:
我正在使用 Spring Boot,并试图在部署时使我的静态资源(CSS、JS、字体)可用。源代码供您查看或从https://github.com/joecracko/StaticResourceError 克隆。
现在我的 CSS、JS 和字体文件对我部署的网站不可见。
这是我的项目目录结构:
这是已编译 JAR 的根目录:我向您保证,这些文件存在于它们各自的文件夹中。
这是我看到的网络错误:
这里是我的 chrome 工具提供的源代码。请注意 bar.css 在这里显示为空。你可以看看我的源代码,看它不是空的。
这是我的主页.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<!-- Main Styles -->
<link rel="stylesheet" href="/css/bar.css" />
<script src="/js/foo.js"></script>
</head>
<body>
<div>Welcome to Foo!</div>
</body>
</html>
这是我的 Web 应用初始化程序 (FooWebAppInitializer.java)
public class FooWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ServletConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
//Spring Security
container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, false, "/*");
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcherServlet", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
dispatcher.addMapping("*.css");
dispatcher.addMapping("*.eot");
dispatcher.addMapping("*.svg");
dispatcher.addMapping("*.ttf");
dispatcher.addMapping("*.woff");
dispatcher.addMapping("*.map");
dispatcher.addMapping("*.js");
dispatcher.addMapping("*.ico");
}
}
这是我的 Servlet 配置 (ServletConfig.java)
@Configuration
@EnableWebMvc
@ComponentScan({"com.foo"})
public class ServletConfig extends WebMvcAutoConfiguration{
@Bean
MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
}
还有,我的 Spring Security Config (WebSecurityConfig.java)
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**"); // #3
}
}
【问题讨论】:
标签: java spring spring-mvc configuration spring-boot