seinecle seinecle - 12 days ago 6
Java Question

How to return a static html page with Spark Java?

A hello world with spark:

get(new Route("/hello") {
@Override
public Object handle(Request request, Response response) {
response.type("text/html");
return "<h1>Hello Spark MVC Framework!</h1>";
}
});


How can I return a static file index.html instead?

Notes:


  • I need this index.html to be in the jar

  • in the spirit of simplicity of spark java, I'd like to avoid as much as possible going through templates, that would be overkill for a static page.


Answer

You can do so by passing the absolute path to your static resources directory in this method:

externalStaticFileLocation("/var/www/public");

Or by passing the relative path in this method:

staticFileLocation("/public");

Call this before setting any route. Create your index.html file in the root of your static resources directory.