USer22999299
USer22999299

Reputation: 5694

How to keep the database connection alive on the server regardless of the HttpServlet

I'm trying to understand how the servlet should work.

I have a Tomcat 8 running the web server. I created a servlet, that extends the HttpServlet class.

public class CollectedItems extends HttpServlet {
    ...
}

There I have the doGet and doPost methods. This class instance will be created, as soon as an http request is sent.

I want to be able to create another class that will maintain my DB connection once, and I will keep it alive instead, that in each call I will create these objects from scratch.

In a normal java application I would have the main method, that launch as soon as you run the program. How does it work in a servlet? Where should I put the class, that the main function start, as soon as the server is up?

The database was just an example, I'm looking for a place, where I can initialize my server objects.

Upvotes: 0

Views: 144

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44854

i'm looking for a place where i can initialize my server objects

In that case consider using a ServletContextListener, this will be loaded when the application starts. From here you can create a singleton object which can be accessible by all your servlets

Upvotes: 2

jun33199
jun33199

Reputation: 155

you can configure a servlet in web.xml,the tomcat will run the servlet when your application running, codes like this:

  <servlet>
    <servlet-name>CollectedItems</servlet-name>
    <servlet-class>com......ClientActionServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>CollectedItems</servlet-name>
    <url-pattern>/CollectedItems</url-pattern>
  </servlet-mapping>

Upvotes: 1

Related Questions