skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    I followed what andrewJames was saying and that worked for me. I was hoping there would be a cleaner way of doing this, as I'm just copy pasting the same code for every endpoint and changing the file path, but this works.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search