Jetty: Pass object from main method to servlet

前端 未结 3 1917
臣服心动
臣服心动 2020-12-18 13:38

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

The most important part of the c

3条回答
  •  太阳男子
    2020-12-18 14:23

    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.

提交回复
热议问题