Learn how to work with Java Servlets

Servlets are programs that execute on the server side of a web connection. Servlets dynamically extend the functionality of a web server.

Servlets vs CGI

Earlier Common Gateway Interface (CGI) programs written in C/C++/PERL was used in the server side, which resulted in serious performance problems. CGI needs creation of a separate process for each client request and was expensive. Moreover CGI programs were not platform independent. Hence, other techniques were introduced including Servlets.

Following are the main features of Servlets:

(1) It executes within the address space of a web server.
(2) It does not require creation of a separate process for each client request.
(3) They are platform independent, because they are written in Java.
Several Web servers supports the Servlet API.
(4) Full functionality of the Java class library is available to a Servlet.

What you need to run Servlets?

(1) Java Servlet Development Kit contains all the class Libraries that a developer needs to create Servlets.
(2) JDK1.2 or higher should have to be installed.
(3) Text Editor preferably Notepad or MS -DOS Editor etc.

You have to compile your source code using javac command after specifying the correct Environment Variables (Path). If you try to compile the code without the correct path, then your code will not compile.

Life Cycle of a Servlet

Like Applets, Servlets are also having a Life cycle. When you execute your Servlet each time, this life cycle is automatically executed. It will execute through a series of methods which are explained below.

  1. (1) User enters URL into a web browser. Browser generates an HTTP request, for this URL and sends it to the Server
    (2) Webserver processes this request and maps request to a particular servlet.
    (3) Server invokes the init() method of the Servlet. This is called only when the servlet is first loaded into memory.
    (4) Servlet invokes the servlets service() method which will process the HTTP request. This method is called for each HTTP Request.
    (5) Server calls destroy() method to free any resources associated with it.

Your First Servlet Program

Type in the following code using a Text Editor and save the file as Helloservlet.java:

import java.io.*;
import javax.servlet.*;
public class Helloservlet extends GenericServlet {
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException {
res.SetcontentType("text/html");
PrintWriter pw = new PrintWriter();
pw.println("<b>HelloWorld"); pw.close(); 
} 
} 

Generic servlet provides functionality that makes it easy to handle requests and responses. service() method inherited from GenericServlet is overridden. The objects req and res handles requests from a client and from a server.

On compilation Helloservlet.java will become Helloservlet.class.

Follow the steps given below to run the Servlet:

Run servletrunner

Type http://localhost:8080/servlet/HelloServlet on the Internet Explorer Address Bar to execute the Servlet

However, this program gives you an overview of the working of Servlets, GenericServlet class is not popularly used in real world programming. Since you are communicating with the server via HTTP, the Java Servlet API provides us with a class called HTTPServlet class which can handle HTTP requests and responses. This means that your servlet can interact with HTML Forms. You may submit information to a database via a Servlet or can develop dynamic applications using sessions and cookies. I will cover all these concepts in detail in a later part of this tutorial.

Working with HTTPServlet class

Enter the following HTML Code using a Text-Editor:

<html>
<head>
<title>
</title>
</head>
<body>
<form action = "http://localhost:8080/servlet/Firstservlet" method = post>
<input type = "submit">
</form>
</body>
</html> 

Now enter the following Java code:

import java.io.*;
import javax.servlet.*;
public class Firstservlet extends HTTPServlet {
public void doPost(HTTPServletRequest req,HTTPServletResponse res) throws
ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw = new PrintWriter();
pw.println("<b>Helloworld</b>"); pw.close(); 
} 
} 

Now, let us examine the above code in detail. First the two Java packages java.io and javax.servlet are imported. The class extends the HTTPServlet class. It overrides the doPost() method of the HTTPServlet class. Two objects req and res are created and the method throws ServletException and IOException. Next the MIME type is specified as text/html.

An object pw is created using the PrintWriter class and println method is invoked which will print HelloWorld in bold font. You can print your text using any HTML Tag. Keep in mind that you have to enclose the tags within the double quotes. Finally, close() method of the PrintWriter class is called to free the memory occupied by the object.

Leave a Comment