How to return a static html page with Spark Java?

大憨熊 提交于 2019-12-03 20:50:35

问题


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.

回答1:


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.




回答2:


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;



来源:https://stackoverflow.com/questions/34197544/how-to-return-a-static-html-page-with-spark-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!