I have a simple Spring Boot Starter Web application. I want to serve several static html files.
I know that I could serve static files with Spring Boot just simply putting then to /static
subdirectory of my src/main/resources
.
When I create file (for example) /static/docs/index.html
, then I could access it via http://localhost:8080/docs/index.html
.
What I want to achieve is to access this file simply with http://localgost:8080/docs
where index.html
is implicitly added by Spring.
I need to serve static files in /static/{path}/index.html
in resources via localhost:8080/{path}
path.
I know that I could manually create mappings in controllers, but when there is many files to serve it becomes annoying.
This will work
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/docs").setViewName("forward:/docs/index.html");
}
}
Or possible solution for all static subdirs (ugly version)
public void addViewControllers(ViewControllerRegistry registry) {
File file;
try {
file = new ClassPathResource("static").getFile();
String[] names = file.list();
for(String name : names)
{
if (new File(file.getAbsolutePath() + "/" + name).isDirectory())
{
registry.addViewController("/" + name).setViewName("forward:/" + name +"/index.html");
}
}
} catch (IOException e) {
// TODO: handle error
e.printStackTrace();
}
}