[英]How to response with HTML page SparkJava
我發現這和這一個答案,但沒有一次成功。 第一個僅適用於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)
檢查getClass().getResource(htmlFile)
的返回值,這可能為null,因為找不到資源。
如果您有文件“ 404.html”和類路徑的根目錄,請將代碼更改為(注意插入“ /”)
get("/404", (req, res) -> helper.renderContent("/404.html"));
我的文件路徑錯誤。 將("404.html")
更改為("public/404.html")
幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.