I am using Spring Boot, and am trying to make my static resources (CSS, JS, Fonts) available when deployed. The source code is available for you to look at or clone from https://github.com/joecracko/StaticResourceError.
Right now my CSS, JS, and Font files are not visible to my deployed website.
Here is my project directory structure:
Here is the root directory of the compiled JAR: I assure you the files are present in their respective folders.
Here is the network error I am seeing:
And here are my sources provided by chrome tools. Note that bar.css appears empty here. You may look at my source code to see that it is not empty.
Here is my homepage.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>
Here is my Web App Initializer (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");
}
}
Here is my Servlet Configuration (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;
}
}
And for kicks, My 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
}
}