Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetty: Pass object from main method to servlet

I have two classes Server (with the main method, starting the server) and StartPageServlet with a Servlet.

The most important part of the code is:

public class Server {
    public static void main(String[] args) throws Exception {
        // some code

        // I want to pass "anObject" to every Servlet.
        Object anObject = new Object();

        Server server = new Server(4000);
        ServletContextHandler context = 
            new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.addServlet(StartPageServlet.class, "/");
        // more code
}

And the StartPageServlet:

public class StartPageServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException
    {
        // Here I want to access "anObject"
    }

How do I do this?

like image 505
Freddy Avatar asked Oct 27 '25 12:10

Freddy


2 Answers

Embedded Jetty is so wonderful here.

You have a few common options:

  1. Direct instantiation of the servlet, use constructors or setters, then hand it off to Jetty via the ServletHolder (can be any value or object type)
  2. Add it to the ServletContext in your main, and then access it via the ServletContext in your application (can be any value or object type).

Examples:

package jetty;

import java.io.IOException;

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.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

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

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

        // Option 1: Direct servlet instantiation and ServletHolder
        HelloServlet hello = new HelloServlet("everyone");
        ServletHolder helloHolder = new ServletHolder(hello);
        context.addServlet(helloHolder, "/hello/*");

        // Option 2: Using ServletContext attribute
        context.setAttribute("my.greeting", "you");
        context.addServlet(GreetingServlet.class, "/greetings/*");

        server.setHandler(context);
        server.start();
        server.join();
    }

    public static class HelloServlet extends HttpServlet
    {
        private final String hello;

        public HelloServlet(String greeting)
        {
            this.hello = greeting;
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("text/plain");
            resp.getWriter().println("Hello " + this.hello);
        }
    }

    public static class GreetingServlet extends HttpServlet
    {
        private String greeting;

        @Override
        public void init() throws ServletException
        {
            this.greeting = (String) getServletContext().getAttribute("my.greeting");
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("text/plain");
            resp.getWriter().println("Greetings to " + this.greeting);
        }
    }
}
like image 116
Joakim Erdfelt Avatar answered Oct 29 '25 01:10

Joakim Erdfelt


Singleton

You want to pass the same single instance to each servlet?

Use the Singleton pattern to create a single instance that is available globally.

The simplest fool-proof way to do that in Java is through an Enum. See Oracle Tutorial. Also see this article and the book Effective Java: Programming Language Guide, Second Edition (ISBN 978-0-321-35668-0, 2008) by Dr. Joshua Bloch.

So no need to pass an object. Each servlet can access the same single instance through the enum.

Per web app

If you want to do some work when your web app is first launching but before any servlet in that web app has handled any request, write a class that implements the ServletContextListener interface.

Mark your class with the @WebListener annotation to have your web container automatically instantiate and invoke.

like image 29
Basil Bourque Avatar answered Oct 29 '25 00:10

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!