【问题标题】:How to response with HTML page SparkJava如何使用 HTML 页面 SparkJava 响应
【发布时间】:2016-10-27 05:10:34
【问题描述】:

我找到了thisthis one 的答案,但它们都不起作用。第一个仅适用于index.html(您不需要指定路径和类似的东西)。第二个解决方案的代码给了我NullPointerException,尽管文件存在并且Spark返回index.html

助手类

class Helper(){
   String renderContent(String htmlFile) {
       try {
           return new String(Files.readAllBytes(Paths.get(getClass().getResource(htmlFile).toURI())), StandardCharsets.UTF_8);
       } catch (IOException | URISyntaxException e) {
           e.printStackTrace();
           mailSendingList.add(e.toString());
       }
       return null;
   }
}

路线

get("/404", (req, res) -> helper.renderContent("404.html"));

例外

java.lang.NullPointerException
at Helper.renderContent(Helper.java:177)
at Main.lambda$main$1(Main.java:33)
at spark.SparkBase$1.handle(SparkBase.java:311)
at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:159)
at spark.webserver.JettyHandler.doHandle(JettyHandler.java:60)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:179)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:451)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:252)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:266)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

    标签: java html spark-java


    【解决方案1】:

    查看getClass().getResource(htmlFile)的返回,这可能是null,因为没有找到资源。

    如果您有文件“404.html”和类路径的根目录,请将代码更改为(注意“/”的插入)

    get("/404", (req, res) -> helper.renderContent("/404.html"));
    

    【讨论】:

    • getResource(htmlFile) 调用的结果是什么?找到这个资源了吗?
    • 它给我一个 NullPointer,但我已经解决了这个问题。请参阅问题下方的评论
    【解决方案2】:

    我的文件路径错误。将 ("404.html") 更改为 ("public/404.html") 有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多