1

I found this and this one answer but none of them worked. The first one works only for index.html(you do not need to specify path and stuff like that). The code from the second solution gives me NullPointerException although the file exists and Spark returns index.html.

Helper class

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;
   }
}

Routes

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

Exception

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)
Community
  • 1
  • 1

2 Answers2

1

check the return of getClass().getResource(htmlFile), this probably is null because the resource is not found.

If you have the file "404.html" and the root of your classpath, change your code to (notice the insertion of '/')

get("/404", (req, res) -> helper.renderContent("/404.html"));
P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66
1

My file path was wrong. Changing ("404.html") to ("public/404.html") helped.

kaqqao
  • 12,984
  • 10
  • 64
  • 118