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.
READ  Understanding Server-side I/O Performance: Node vs PHP vs Java vs Go

Your First Servlet Program

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

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">import java.io.*;
import javax.servlet.*;
public class Helloservlet extends GenericServlet {
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException {
res.SetcontentType(&quot;text/html&quot;);
PrintWriter pw = new PrintWriter();
pw.println(&quot;<span style="color: #0000ff">&lt;</span><span style="color: #800000">b</span><span style="color: #0000ff">&gt;</span>HelloWorld&quot;); 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:

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px"><span style="color: #0000ff">&lt;</span><span style="color: #800000">html</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">head</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">title</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">title</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">head</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">body</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">form</span> <span style="color: #ff0000">action</span> = <span style="color: #0000ff">&quot;http://localhost:8080/servlet/Firstservlet&quot;</span> <span style="color: #ff0000">method</span> = <span style="color: #0000ff">post</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">input</span> <span style="color: #ff0000">type</span> = <span style="color: #0000ff">&quot;submit&quot;</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">form</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">body</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">html</span><span style="color: #0000ff">&gt;</span> 

Now enter the following Java code:

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">import java.io.*;
import javax.servlet.*;
public class Firstservlet extends HTTPServlet {
public void doPost(HTTPServletRequest req,HTTPServletResponse res) throws
ServletException,IOException {
res.setContentType(&quot;text/html&quot;);
PrintWriter pw = new PrintWriter();
pw.println(&quot;<span style="color: #0000ff">&lt;</span><span style="color: #800000">b</span><span style="color: #0000ff">&gt;</span>Helloworld<span style="color: #0000ff">&lt;/</span><span style="color: #800000">b</span><span style="color: #0000ff">&gt;</span>&quot;); 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.

READ  Two Quick Ways to Perform ASP.NET Authentication

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 Reply

Your email address will not be published.