A Simple Servlet Example Tutorial using Tomcat and Eclipse

A Simple Servlet Example

This is a simple servlet example using tomcat and eclipse. servlet-example-in-tomcat-eclipse

It answers the questions like, what is a servlet? How a servlet works in the Tomcat container? The life cycle of a servlet etc.

Servlet Example using Tomcat and Eclipse

What is a Servlet?

A Servlet is a server side java component that can process the request sent by a browser and send back response to it. A Servlet is a Simple java class implementing the Servlet interface in the javax.servlet interface. The response sent by the Servlet back to the browser is purely html. Servlets can execute inside a servlet container like tomcat,weblogic etc.

The javax.servlet package contains all the classes and interfaces that will be required to build a servlet.

Interfaces inside the javax.servlet package

How to Create a Servlet?

To create a servlet you have to implement the Servlet interface and provide implementation of all the methods in that interface.. The important methods are init ,service, destroy.So while creating a servlet we are actually defining all the required methods like init,service,destroy. When the request for a servlet reaches Tomcat, it will call the methods following a particular order which is called the life cycle of a Servlet..

How Tomcat Works?

When a request for a servlet reaches Tomcat from a browser, the first thing Tomcat does is it  finds out weather an object of that servlet is loaded or not. If not loaded tomcat loads a new object for that Servlet. If loaded tomcat compares the time stamp of the loaded Servlet object with the Servlet class file. If the loaded servlet object is older then the servlet class file, tomcat loads  a new servlet object that will process the request.

Life Cycle of a Servlet

Tomcat will first call the init method, then the service method. destroy method will be called just prior to the destruction of the servlet instance the init method gets called only once for an object The things that may be done once for an application can be put in the init method What ever is the functionality of the servlet should be placed in side the service method

If the same servlet is opened from different browsers the output will be

For private training  check the link– Online Java J2ee Training