With the fine way to serve static html/css/js resources from src/main/resources/static
, is there a way to have some form of url abstraction?
Precisely, I would like to remove the .html
ending from the urls.
html extension can be easily removed by editing the . htaccess file.
Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
An HTML file is nothing more than plain ASCII text, but all HTML files must have a special file extension for web browsers to recognize them. This extension is either . htm OR . html.
To return html static file without extension is the same as return view name from any of templates engines (jsp, theamleaf, freemarker), the thing here you do not need to run any templates processing on view file, you just return it as it is.
Add code below to your Spring configuration:
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("pages/");
internalResourceViewResolver.setSuffix(".html");
return internalResourceViewResolver;
}
Be careful /pages
folder should be inside your ResourceLocation
, that means ResourceLocation + "/pages/" + pageName.html
in browser should give you desired file (if you already configured servicing of static files it will not be a problem for you to find your ResourceLocation, check method addResourceHandlers
in your WebMvcConfigurer)
Now at your WebMvcConfigurer you can add:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/admin").setViewName("admin");
registry.addViewController("/contact").setViewName("contact");
registry.addViewController("/error").setViewName("index");
}
or just use it, as you would use it in usual view resolver within MVC controller
@GetMapping("/")
public String greeting() {
return "index";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With