首页 > 代码库 > The use of servlet

The use of servlet

Servlet is a java code run in the server such as Tomcat.

How to create a servlet?

  1.Create a class extends HttpServlet (or implements the Servlet interface or extends the GenericServlet)

  2.Override the doPost and doGet (if implements the Servlet interface , you should override all the methods : init() service() getServletConfig() getServletInfo() destroy())

  3.Configure the Servlet in the web.xml.

The structure of Servlet:

  javax.servlet.Servlet interface

    ----->  javax.servlet.Genericservlet abstract class

      ------> javax.servlet.http.HttpServlet

        ------> the class extends or implements xxx you defined by yourself

The life-cricle of servlet:

  1.create the servlet and call the init() to initialize the servlet.

  2.process the request via service().

  3.destroy the servlet via destroy() and the garbage collect the servlet.

When we create the serlet , the first access to the servlet will create the object of servlet constructor , then call the init() method . But the init() will be called once.

Importantly , there will start a thread to call the service() . Because the web apps are multi-thread application.

When we access to the server, there will open a new thread to call the service.

The servlet object usually created once and it stays at the memory for a long time.

When the server stop or the servlet object was destroyed the destroy() method will be called.

Notice:

  if you create the member variables in servlet , may lead to the secure problems.

  So, we should avoid to create member variables in servlet. If must, we should synchronize it.

About doGet() and doPost():

  According to the url, we can find the servlet from the web.xml to call the service(). The service() in HttpServlet is extended from GenericServlet and includes doGet() and doPost().

  Tell from the method name, the service could tell which method to use. And here involves a design pattern: Template method model.

 

 

 

 

 

 

 

 

 

 

                    

 

The use of servlet