Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 394
seinecle Avatar asked Dec 10 '15 09:12

seinecle


2 Answers

I know I am very late to the party, You can do the following:

  1. staticFiles.location("/public"); // create a folder called 'public' under 'src/main/resources' folder

  2. When the app is initialized, call the above method before any of the routes or requests. This is very important.

  3. In your "controller", you can add it like this:

response.redirect("test.html"); return null;

like image 138
UVM Avatar answered Oct 22 '22 12:10

UVM


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.

like image 34
Laercio Metzner Avatar answered Oct 22 '22 14:10

Laercio Metzner