Yu Sasaki's Blog

Icon

プログラミングとか英語とかの練習!

Learning the structure of Servlet

Today I learned Servlet in EJB605 class, and felt like learning it in more detail so I’ve read through some chapters of Java book.

Here are my understandings:

In the javax.servlet package, there is an interface called “Servlet” and followings are abstract methods to be overridden in future implemented classes.

Servlet interface

  • service(ServletRequest, ServletResponse)
  • init(ServletConfig)
  • destroy()
  • (a few more methods follow)

The interface is implemented by javax.servlet.GenericServlet class, which is an abstract class again, and that class is inherited by javax.servlet.http.HttpServlet class, which is now all set for being inherited by a Servlet we can implement. Here’s the hierarchy.

  • Servlet interface
    • implemented by GenericServlet class
      • extended by HttpServlet class

        • extended by our Servlet class (the most derived)

After a Servlet gets loaded by Web container, it initiates an object by calling the constructor of the Servlet. Then it calls init() method, and service() method follows. In the service() method, one of doX() method is called (or used to delegate another doX) to process the client request. After finishing the service, destroy() method is called to finish the life of Servlet.

The service() method has two parameters – HttpServletRequest and HttpServletResponse.

The interesting thing here to me is both are interfaces extended (not implemented) from the other interfaces – ServletRequest and ServletResponse.

  • ServletRequest interface
    • extended by HttpServletRequest interface
  • ServletResponse interface
    • extended by HttpServletResponse interface

I didn’t know the fact that an interface can extend another interface…so this was an eye opener. Anyway, the service() method has parameters of references for two objects that implemented HttpServletRequest and HttpServletResponse interfaces polymorphically. How the actual classes for these interfaces implement their methods are all dependent on vendor, so we do not need to care about it. A variety of methods are available in each request and response objects.

See you!

Advertisements

Filed under: EJB605, Java, Servlets & JSP

One Response

  1. snimavat says:

    Nice explanation,
    jsptube.com has many more servlet tutorials, this servlet example is also very good

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: