4

I have a servlet which I want to return a resource, or at least the html from the resource, index.html which is located in my webapps folder.

I'm very new and haven't been able to find anything. Here's my code I would appreceiate any help!

public static void main(String[] args){
    Server server = new Server(8080);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase("./target/classes/webapp");

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    ServletHolder indexHolder = new ServletHolder(new IndexServlet());
    context.addServlet(indexHolder, "/index");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, context, new DefaultHandler()});
    server.setHandler(handlers);

    try {
        server.start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

This is my current doGet method. The print staement currently is the string value of the index.html file that I would like the servlet to return.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.getWriter().print(
            "<!doctype html>\n" +
            "<html>\n" +
            "<head>\n" +
            "<meta charset=\"utf-8\">\n" +
            "<title>Form Page</title>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <form id=\"jetty-form\" name=\"user-form\" method=\"post\">\n" +
            "        <label for=\"username\">Username:</label>\n" +
            "        <input type=\"text\" name=\"username\" id=\"username\">\n" +
                            "<input type=\"submit\">" +
            "    </form>\n" +
            "</body>\n" +
            "</html>");

}
dur
  • 13,039
  • 20
  • 66
  • 96
Dan Gardner
  • 493
  • 7
  • 16

1 Answers1

2

Do not use ResourceHandler and ServletContextHandler together. (prior answer)

Drop the ResourceHandler entirely.

Drop the IndexServlet (you don't need it).

Create a src/main/webapp/index.html (if using Maven and a WAR project type) and write the HTML as HTML.

The ServletContextHandler needs a Resource Base.

The Resource Base should be a full (absolute) path (not relative) to your post-processed static content. If your build copies/creates/modifies resources, you need to be aware of that and use an alternate directory location. It is possible to use a jar:file:// directory location as well.

When you run / debug / test from your IDE you are not using a JAR packaged static resources, so your Resource Base determination should be smart enough to use alternate locations depending on how it is being executed. (maven command line, gradle command line, IDE specific quick run, IDE maven run, IDE gradle run, etc ...)

Your ServletContextHandler should have a DefaultServlet added to its servlet tree (this is what actually serves static resources)

Example: DefaultServletFileServer.java (from embedded-jetty-cookbook project)

import java.net.URI;
import java.net.URL;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;

public class DefaultServletFileServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);
        server.addConnector(connector);

        // Figure out what path to serve content from
        ClassLoader cl = DefaultServletFileServer.class.getClassLoader();
        // We look for a file, as ClassLoader.getResource() is not
        // designed to look for directories (we resolve the directory later)
        URL f = cl.getResource("static-root/hello.html");
        if (f == null)
        {
            throw new RuntimeException("Unable to find resource directory");
        }

        // Resolve file to directory
        URI webRootUri = f.toURI().resolve("./").normalize();
        System.err.println("WebRoot is " + webRootUri);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(Resource.newResource(webRootUri));
        server.setHandler(context);

        ServletHolder holderPwd = new ServletHolder("default",DefaultServlet.class);
        holderPwd.setInitParameter("dirAllowed","true");
        context.addServlet(holderPwd,"/");

        server.start();
        server.join();
    }
}
Community
  • 1
  • 1
Joakim Erdfelt
  • 41,193
  • 5
  • 78
  • 124
  • The code above is specifically designed for embedded jetty execution from a jar with its static resources also included in the jar. – Joakim Erdfelt Nov 08 '17 at 17:54