Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static html files omitting the .html extension in the url

Tags:

spring-boot

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.

like image 396
yglodt Avatar asked Nov 03 '16 14:11

yglodt


People also ask

How do I remove .html extension from URL?

html extension can be easily removed by editing the . htaccess file.

Are HTML files static files?

Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.

How do you add an extension to HTML?

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.


1 Answers

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";
}
like image 183
Sergey Luchko Avatar answered Oct 11 '22 13:10

Sergey Luchko