0👍
Spring boot provides plug and play type facilities that is the beauty of spring boot. Same thing is applicable here for serve static content from locations in web application with spring boot. By default spring boot serves static resources from classpath as default property:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
And default static path pattern is:
spring.mvc.static-path-pattern=/**
But it is good practice to provide other than default.
However spring boot also provides customization of that configuration programmatically as well by implementing WebMvcConfigurerAdapter
.
@EnableAutoConfiguration
public class AddCustomLocations {
@Bean
WebMvcConfigurer configurer () {
return new WebMvcConfigurerAdapter() {
@Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").
addResourceLocations("classpath:/my-custom-location/");
}
};
}
public static void main (String[] args) {
SpringApplication app =
new SpringApplication(AddCustomLocations.class);
app.run(args);
}
}
Now add new static content like src/main/resources/new-custom-location/page1.js
and when url pattern like http://localhost:8080/pages/page1.js
found then page1.js will served as static resource.
Now for templates/HelloWorld.html
, default properties modification is required (assumes folder templates
is already there):
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html
Corresponding html pages under directory /templates/
will be rendered by viewResolver.
Edited Answer:
If you are using @EnableWebMvc
then just remove it. Your problem should be resolved.
If still problem is not resolved then override addViewControllers(ViewControllerRegistry registry)
method of class WebMvcConfigurerAdapter
as we have done in earlier code. Add below code snippet on the above code after addResourceHandlers (ResourceHandlerRegistry registry)
method.
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/test").setViewName("testPage");
}
prefix /templates/
and Suffix .html
will be added by view resolver.