Search code examples
url-routingjavalin

Removing .html from end of url in javalin


I'm using Javalin to serve my static web pages, which I've never done before. I know it's possible in Nginx to remove the .html from the end of your url but still route to the correct page, for example mysite.com/login would replace mysite.com/login.html but still point towards my login.html file. Is this possible in Javalin?

I've tried looking into the config (StaticFileConfig) but couldn't seem to find anything that would solve this problem


Solution

  • Here are two examples of what was discussed in the comments to the question, for future visitors:

    The first example assumes there is a simple HTML file in the application's resources/html folder.

    The test.html file:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Test</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body>        
            <div>Hello world.</div>
        </body>
    </html>
    

    The /test handler:

    public static void main(String[] args) {
    
        Javalin.create(config -> {
        })
            .get("/test", ctx -> {
                ctx.contentType(ContentType.TEXT_HTML);
                InputStream in = App.class.getResourceAsStream("/html/test.html");
                ctx.result(in);
            })
            .start(8080);
    }
    

    If you choose to configure Javalin with Thymeleaf, and if you place your HTML file in the default location expected by Thymeleaf (resources/thymeleaf), then you can do this:

    .get("/test", ctx -> {
        Map<String, Object> model = new HashMap<>();
        ctx.render("test.html", model);
    })
    

    In this case, the model used by Thymeleaf for rendering is empty because you don't need to make any substitutions in your HTML file (it's not a template). But it's a short step from this to using dynamic Thymeleaf templates.