Ravikiran R
Ravikiran R

Reputation: 65

Building a web application with embedded-jetty and jersey .. with request dispatching

I am setting a web application with embedded jetty and jersey .As i am fairly new with concepts, it is difficult to load a sample webpage index.html. When i target it as localhost:8989/myServlet i see the code flow through my servlet . But request dispatcher always returns null.

Please let me know with this:

Main class:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;


public class MainApp {
    public static void main(String[] args) throws Exception {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8989);
        jettyServer.setHandler(context);

        ServletHandler handler =new ServletHandler();
        handler.addServletWithMapping(MyServletHandler.class,"/myServlet");


        jettyServer.setHandler(handler);

        ServletHolder jerseyServlet = context.addServlet(
                org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                Entry.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
}

Myservlet class:

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServletHandler extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Control is in servlet");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.html"); // this returns null. hence i am unable to request dispatch to view the html webpage.


    }

}

I use Maven to build the application and i have placed index.html in src/main/resources directory

Upvotes: 1

Views: 1171

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49515

This works, but you'll have to properly setup the ServletContext so that the request.getRequestDispatcher() can do something.

For starters, your ServletContextHandler MUST have a Resource Base setup.

You'll have to setup a DefaultServlet so that the request dispatcher can be returned properly.

You'll also have to use embedded-jetty properly, don't use ServletHandler directly like that. Use the ServletHolder if you must, but otherwise just use the ServletContextHandler directly.

Here's an example of this behavior.

Run with a System Property of baseResource pointing to a directory where you have a index.html.

package jetty.dispatching;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;

import static java.nio.charset.StandardCharsets.UTF_8;

public class DispatchingToDefaultServletDemo
{
    public static void main(String[] args) throws Exception
    {
        DispatchingToDefaultServletDemo demo = new DispatchingToDefaultServletDemo();

        try
        {
            demo.startServer();
            demo.makeRequests();
        }
        finally
        {
            demo.stopServer();
        }
    }

    private Server server;

    public void startServer() throws Exception
    {
        server = new Server(8989);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        // Must have Resource Base for proper ServletContext (even if it points to an empty URI directory in a JAR file)
        context.setBaseResource(getBaseResource());
        // Don't use ServletHandler directly!
        context.addServlet(MyServletHandler.class, "/myServlet");
        // Add DefaultServlet last on ServletContextHandler to be able to serve content from resource base.
        // It must be named "default" (per servlet spec)
        ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
        defaultHolder.setInitParameter("dirAllowed", "true");
        context.addServlet(defaultHolder, "/"); // this is the default url-pattern

        HandlerList handlers = new HandlerList();
        handlers.addHandler(context);
        handlers.addHandler(new DefaultHandler()); // always last in handler tree

        server.setHandler(handlers);

        server.start();
    }

    public Resource getBaseResource() throws IOException
    {
        String baseResourceLocation = System.getProperty("baseResource");
        if (baseResourceLocation == null)
        {
            baseResourceLocation = System.getProperty("user.dir");
        }
        Resource resource = Resource.newResource(baseResourceLocation);
        System.out.println("Base Resource is " + resource);
        return resource;
    }

    private void stopServer() throws Exception
    {
        server.stop(); // use .stop() NOT .destroy()
    }

    private void makeRequests()
    {
        performGET("/myServlet");
        performGET("/");
    }

    private void performGET(String requestPath)
    {
        try
        {
            URI uri = server.getURI().resolve(requestPath);
            System.out.println("Requesting GET on " + uri);
            HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
            System.out.println("  Response Status code = " + http.getResponseCode());
            try (InputStream in = http.getInputStream())
            {
                System.out.println("  Response Body: " + IO.toString(in, UTF_8));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static class MyServletHandler extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.html");
            System.out.println("request Dispatcher = " + requestDispatcher);
            requestDispatcher.forward(request, response);
        }
    }
}

The output ...

$ java -DbaseResource=/home/joakim/code/jetty/bases/listing-base/rez/welcomish/ -classpath <..snip..> jetty.dispatching.DispatchingToDefaultServletDemo

2019-04-18 15:15:15.595:INFO::main: Logging initialized @180ms to org.eclipse.jetty.util.log.StdErrLog
Base Resource is file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/
2019-04-18 15:15:15.678:INFO:oejs.Server:main: jetty-9.4.15.v20190215; built: 2019-02-15T16:53:49.381Z; git: eb70b240169fcf1abbd86af36482d1c49826fa0b; jvm 1.8.0_192-b12
2019-04-18 15:15:15.725:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2019-04-18 15:15:15.726:INFO:oejs.session:main: No SessionScavenger set, using defaults
2019-04-18 15:15:15.727:INFO:oejs.session:main: node0 Scavenging every 660000ms
2019-04-18 15:15:15.736:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,AVAILABLE}
2019-04-18 15:15:15.747:INFO:oejs.AbstractConnector:main: Started ServerConnector@3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.747:INFO:oejs.Server:main: Started @333ms
Requesting GET on http://127.0.1.1:8989/myServlet
request Dispatcher = Dispatcher@0x5d8c6ff2{null,/index.html}
  Response Status code = 200
  Response Body: <h1>My welcomish HTML</h1>

Requesting GET on http://127.0.1.1:8989/
  Response Status code = 200
  Response Body: <h1>My welcomish HTML</h1>

2019-04-18 15:15:15.827:INFO:oejs.AbstractConnector:main: Stopped ServerConnector@3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.827:INFO:oejs.session:main: node0 Stopped scavenging
2019-04-18 15:15:15.829:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler@482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,UNAVAILABLE}

Process finished with exit code 0

Upvotes: 1

Related Questions