Introduction to Servlets

October 7 2009one Commented

Categorized Under: Java

This tutorial is based on the following software environment.

Windows Vista Home Premium, Eclipse 3.5, JDK 1.6, Tomcat 6

For creating dynamic web applications we need some server resources which process user requests and send response back to user. Typical examples are processing HTML form, database query and sending dynamic HTML content back to user. Early days, we used CGI programs based on scripting languages like Perl, PHP etc. Java Servlets is an alternative to CGI programs based on popular Java programming language.

Servlet API consists two packages.

  • javax.servlet – classes and interfaces for generic servlet implementation.
  • javax.servlet.http – classes and interfaces mainly used for HTTP based communication.

 All servlets must implement Servlet interface which is part of javax.servlet package. Servlet interface define some methods including life cycle methods and methods for accessing servlet properties. Unlike CGI program, servlet is initialized only once rather than creating multiple instances for each and every request. The following life cycle methods are defined in Servlet interface.

  • init(ServletConfig config) – this method is called only once during the life cycle of the servlet. ServletConfig is a configuration object used for initializing servlets by servlet container. This object provides initialization parameters for servlet. ServletConfig object is used to get reference of ServletContext object which has application level scope.
  • destroy() – When the servlet container do not want to keep the reference of a servlet, it calls the destroy() method. This is again called only once during the life cycle of the servlet.
  • service(ServletRequest req, ServletResponse res) – service method is called for each and every request unlike init() and destroy() methods which are called only once throughout servlet life cycle.

So let us summarize the stuff.

On loading the server, the servlet container checks whether the servlet should be initialized during start-up. This is defined in configuration file. If yes, the servlet is initialized.

During initialization it calls the init() method. This method may be used to call any resources which are shared by all requests. For eg, database connection object.

When the request comes, the container checks whether the servlet is already initialized. If not, it initializes the object.

service() method is called for every request. The container creates ServletRequest and ServletResponse objects and pass to this method. This method process the request using ServletRequest object and send response back to client using ServletResponse object.

destroy() method is called during server shutdown. We may close any shared resources here like database connection object.

For our convenience Servlet API provides two classes which implement Servlet interface.

GenericServlet – An abstract class which is protocol independent may be used for generic purposes. It has service() method which we may be used to override for every request. Similarly init() and destroy() methods may also be overridden.

HttpServlet – An abstract class which is extended from GenericServlet based on HTTP protocol. In most cases, we extend this class for web applications. Since this is based on HTTP protocol, it has additional methods for handling different types of HTTP requests. User has to override at least one of these methods based on request type. Do not override service() method as this is used to dispatch the request to appropriate request handler methods. The following methods are available.

  • doGet(HttpServletRequest req, HttpServletResponse resp) - for managing GET requests.
  • doPost(HttpServletRequest req, HttpServletResponse resp) - for managing POST requests.

In addition to the above methods, there are methods for delete, trace, head, options and put request types. Generally in a secure web environment, we allow only GET and POST requests. HttpServletRequest and HttpServletResponse objects are used for managing request and response.

If you want to know more about HTTP request types, there are plenty of resources available in web, so please refer them.

The servlet API is available in JAR file which is required for compiling and executing servlets. If you are using servlet container like Tomcat this JAR file is shipped with it. It is also shipped with Java EE SDK.

For running servlets within servlet container we have to create web application. A typical Java web application consists of static resources like html files, images, CSS/JavaScript files etc and dynamic web components like servlets and JSPs. Every web application should maintain a directory structure and servlet classes should reside in /WEB-INF/classes folder under application root folder. There is a configuration file called web.xml file is associated with every application where we should define servlet properties, URL mappings etc. If you are using Eclipse IDE with Tomcat plugin, it automatically compiles servlet classes and put in /WEB-INF/classes directory and make necessary entries in web.xml deployment file.

OK, now let us create a simple servlet example. If you haven’t had Eclipse IDE with Tomcat , refer the following tutorial.

Installing and Configuring Eclipse with Tomcat in Windows

 Open Eclipse. Java EE perspective is the default perspective. If you are not sure go to Window–>Open Perspective–>Other. Select Java EE and click OK.

Go to File–>New–>Dynamic Web project. Project Wizard appears.

servletexample_1

 Give the project name as ServletExample. All other options do not require modification if you are using Eclipse with Tomcat as server. If you have configured multiple servers you may change the target runtime.

servletexample_2

 Click Finish button. Now we have to add the project under server. Go to server window, right click on server entry and select Add and Remove. Move the project from left to right window in properties box. Click Finish button.

 servletexample_3

OK, now the project is added under server. Let us create a servlet. All servlet classes should be defined in Java Resources (src) folder. In project explorer expand the project. Right click on src folder and select New–>Servlet.

servletexample_4

Create Servlet wizard appears. Specify the package name as example and Class name as FirstServlet. Press Next button.

servletexample_5

 Next screen is about URL Mappings for servlet related to deployment descriptor. Keep it as default and press Next button.

Uncheck the option Constructors from superclass. Uncheck the option doPost method. We just require doGet method stub which we want to override in our example. Press Finish button.

 servletexample_6

FirstServlet.java file is opened in editor. Now paste the following code in doGet method skeleton.

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("This is my first servlet");

We have to write one import statement for PrintWriter class. Add the following statement just below other import statements in top of the file. Save the file.

import java.io.PrintWriter;

servletexample_7
 OK, now our servlet is ready. Now let us check the servlet. Go to server window and start the server. Once server is started go to browser, paste the following URL and hit enter.

http://localhost:8080/ServletExample/FirstServlet

If you could see the text “This is my first servlet” in browser, you have successfully created your first servlet. If you are using any other application server this URL may be different. Also the port may be different if you change the default Tomcat port. Now let us walk through the code.

When the servlet is called, doGet() method is executed by servlet container. We set the content type of response object using setContentType() method. In our case it is html text. Optionally you may give character encoding also like utf-8. PrintWriter object is used to write character stream output. We send the output to the browser using println() method.  

Note: response.setContentType() method should be called before writing any output like out.println() method.

 cheers,

One Response to “Introduction to Servlets”

  1. Mariano says:

    Thank you so much! This was the first tutorial about JSP and Servlets that i’ve read and understood every single word you said so far!!!

Leave a Reply

*