Search code examples
javaspark-java

With Java Spark how do I send a html file as a repsonse


How do I use spark to return an existing page

I have the example working where I just return some text

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

I have changed to

import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files


Solution

  • I suppose that C:\\HtmlFolder\\is not in your classpath.

    To serve external resources (out of the classpath) you need to use staticFiles.externalLocation() + System.getProperty()

    Example:

    staticFiles.externalLocation(System.getProperty("myDir"));
    

    Check Spark Static Files Documenation if you need to know more about this.

    EDITED:

    Configure external locatios as above and the, in your get, do something like

    get("/hello", (req, res) -> {res.redirect("/Report00001.html");});

    (I'm not sure now if shoul be "/Report00001.html" or "Report00001.html")