htmlstaticembeddedjetty

Serving static html files using DefaultServlet on embedded Jetty


I'm working on a project that needs to be self contained so I've decided to embed Jetty in my app. I'm gonna be serving static HTML pages, a few JSP pages, and also will be using some custom servlets. I've found a perfect example of how to setup the embedded Jetty to accomplish all of this (http://thinking.awirtz.com/2011/11/03/embedded-jetty-servlets-and-jsp/), however, since this is the first time I'll be using Jetty and working with JSP pages or servlets, I've got a few basic questions.

Here's the code (as found in the link above):

class RunServer {
  public static void main(String args[]) {

    System.out.println("Initializing server...");
    final ServletContextHandler context =
      new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase("webapp");

    context.setClassLoader(
        Thread.currentThread().getContextClassLoader()
    );

    context.addServlet(DefaultServlet.class, "/");

    final ServletHolder jsp =
      context.addServlet(JspServlet.class, "*.jsp");
    jsp.setInitParameter("classpath", context.getClassPath());

    // add your own additional servlets like this:
    // context.addServlet(JSONServlet.class, "/json");

    final Server server = new Server(8080);
    server.setHandler(context);

    System.out.println("Starting server...");
    try {
        server.start();
    } catch(Exception e) {
        System.out.println("Failed to start server!");
        return;
    }

    System.out.println("Server running...");
    while(true) {
        try {
            server.join();
        } catch(InterruptedException e) {
            System.out.println("Server interrupted!");
        }
    }
  }
}

I've added an additional custom servlet and I got that working great, however, I'm having issues with the static content (ie: HTML files). I keep getting "file not found" errors when trying to access them. I'm pretty sure that's because I'm not 100% sure where I should be placing my HTML files. I'm assuming that the line that says "context.setResourceBase("webapp");" is the line that tells the various servlets where to look for the files (ie: resources), however, I'm not sure what "webapp" actually points to. Is it a folder, a class name, an actual file?

I highly appreciated any help on what "webapp" actually is (or points to), and also where to put my static files in my project.

Thanks, Harry


Solution

  • webapp is the directory you should create and place your static files in. :) If you have a maven project it'll be "src/main/webapp" in the root of your project.