问题
After using JHipster on a couple of new projects recently (Highly recommended ! Amazing work !), I am trying to back-port some of the concepts into an older webapp, essentially migrating it to Spring Boot and Angular.
In Spring Boot, the default location for static web resources (HTML, JS, CSS, etc.) is in a directory called public
, static
or resources
located at the root of the classpath. Any of these directories will be picked up by spring boot and files in them will be accessible via HTTP.
In JHipster the web files are in the src/main/webapp
directory. Which is the directory used by default in a classic Maven WAR project.
I like this better because :
- it more clearly separates the static web stuff from the classpath resources used by the Java code
- the nesting is less deep (we already have enough levels of directories nesting with Maven as it is!).
But if I just create webapp directory in my project and put my HTML files in it, they are not available via HTTP, and the build process creates the WEB-INF
directory structure in it. I don't want that, and in JHipster this is not the case.
How can I configure Spring Boot to behave like it does in JHipster ?
For those not familiar with JHipster : How can I instruct Spring Boot to serve static files from a different folder, no included in the classpath ?
回答1:
You can try following configuration. The idea should be pretty straight forward. It does register artifacts in assets
directory.
public class AppMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Including all static resources.
registry.addResourceHandler("/assets/**",
"/css/**",
"/img/**",
"/js/**"
).addResourceLocations("/assets/",
"/css/",
"/img/",
"/js/"
).resourceChain(true)
.addResolver(new PathResourceResolver());
super.addResourceHandlers(registry);
}
}
来源:https://stackoverflow.com/questions/35632175/how-to-change-the-way-spring-boot-serves-static-files