You are on page 1of 16

3.1.2 What Is a Servlet?

 A servlet is a small Java program that runs within a Web server. 



 Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper Text
 Transfer Protocol. 
 Servlet is an opposite of applet as a server-side applet. 
 Applet is an application running on client while servlet is running on server. 

 Servlets are server side components that provide a powerful mechanism for developing web
applications. 

 Using servlets we can create fast and efficient server side applications and can run it on any servlet
 enabled web server. 
 Servlet runs entirely inside the JVM (Java Virtual Machine). 
 Since the servlet runs on server side so it does not depend on browser compatibility. 

“The Helper Application is nothing but a SERVLET”

Request

Servlet

Client Response Server


 The content of the dynamic web pages need to be generated dynamically. 

 In the early days of the Web, a server could dynamically construct a page by creating a separate
process to handle each client request. 

 The process would open connections to one or more databases in order to obtain the necessary
information. 

 It communicated with the Web server via an interface known as the Common Gateway Interface
(CGI). 

3 A Simple JAVA Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req ,HttpServletResponse
res)throws ServletException,IOException{
res.setContentType(“text/html”)
PrintWriter out=res.getWriter();
out.println("<html>“);
out.println("<head><title>Java
Servlet</title></head>"); out.println("<body>“);
out.println(“<p> My First Servlet program </p>
“); out.println("</body></html>");
}}

 A java Servlet is a java class that reads request sent from a client and responds by sending
information to the client. 

 The java class must extend HttpServlet and override the Httpservlet’s doGet() or doPost()
 methods 

 doGet() used when request is sent using the METHOD=“GET” attribute of HTML 

 doPost() used when request is sent using the METHOD=“POST” attribute of HTML 
 Both doGet() and doPost() requires two arguments 
 The first argument is an HttpservletRequest object 
 The secons argument is an HttpservletResponse object 
 The HttpSevletRequest used to receive request from cleint. 
 The HttpServletResponse is used to Respond to Client. 

 (format of data response depends on client, ex: data given is in the form of a HTML or XML
 page if the client is a browser) 
 Both throws ServletExcetion and IOException 
3.4 Servlet Lifecycle
• The Servlet lifecycle is simple, there is only one main state – “Initialized”.

Init can be Destroy can be


overriden to open Does not exist overridden to
DB connections Cloase DB
connections

constructor()
destroy()
init()

Initialized

Service() Executes doGet() or doPost()

 init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a
 servlet. 
 They are implemented by every servlet and are invoked at specific times by the server. 

Procedure:
 First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server. 

 Second, this HTTP request is received by web server, web server maps this request to a particular
 servlet. 
 The servlet is dynamically retrieved & loaded into the address space of the server. 

 Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
 is first loaded into memory. 
 It is possible to pass initialization parameters to the servlet so it may configure itself. 

 Fourth, the server invokes the service ( ) method of the servlet. This method is called to process
 the HTTP request. It may also formulate an HTTP response for the client. 
 The service( ) method is called for each HTTP request. 

 Finally, the server may decide to unload the servlet from its memory. The server calls the
destroy( ) method to relinquish any resources such as file handles that are allocated for the
servlet. 
The Servlet API

Packages

The javax.servlet package contains a number of classes and interfaces


that describe and define the contracts between a servlet class and the runtime
environment provided for an instance of such a class by a conforming servlet
container.

The javax.servlet.http package contains a number of classes and


interfaces that describe and define the contracts between a servlet class running
under the HTTP protocol and the runtime environment provided for an instance of
such a class by a

The javax.servlet Package

 The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. 

Interface Summary
RequestDispatcher Defines an object that receives requests from the client and sends them
to any resource (such as a servlet, HTML file, or JSP file) on the server.
Servlet Defines methods that all servlets must implement.
ServletConfig A servlet configuration object used by a servlet container to pass
information to a servlet during initialization.
Defines a set of methods that a servlet uses to communicate with its servlet
ServletContext container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file.
ServletRequest
Defines an object to provide client request information to a servlet.
ServletResponse Defines an object to assist a servlet in sending a response to the client
The Servlet Interface Methods:

Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being
taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup
parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
void init( ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is being
placed into service.
void service( ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a request.

The following table summarizes the core classes that are provided in the javax.servlet
package.

Class Summary
GenericServlet Defines a generic, protocol-independent servlet.
Provides an input stream for reading binary data from a client
ServletInputStream request, including an efficient readLine method for reading data
one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
This is the event class for notifications of changes to the attributes
ServletRequestAttributeEvent of the servlet request in an application.
ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

The GenericServlet Class

 The GenericServlet class provides implementations of the basic life cycle methods for a servlet. 
 GenericServlet implements the Servlet and ServletConfig interfaces. 
 In addition, a method to append a string to the server log file is available. 
The signatures of this method are shown
here: void log(String s)
void log(String s, Throwable e)
 Here, s is the string to be appended to the log, and e is an exception that occurred. 


The Servlet Exception Classes 

 javax.servlet defines two exceptions. 
 The first is ServletException, which indicates that a servlet problem has occurred. 

 The second is UnavailableException, which extends ServletException. It indicates that a
servlet is unavailable. 

3.6 Reading Servlet Parameters

 The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request. 

 The example contains two files. A Web page is defined in PostParameters.htm and a servlet is
defined in PostParametersServlet.java. 

File Name: PostParametersServlet.java

package
ServletPrograms; import
java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;

public class prog2 extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>user
password</title></head>"); out.println("<body>");
String username=request.getParameter("username");
String password=request.getParameter("password");
out.println("username = "+username);
out.println("<br>");
out.println("password = "+password);
out.println("</body></html>");
out.close();
}
}
File Name: PostParameters.html

<html>
<body>
<form action="prog2"
method="post"> <table>
<tr>
<td><B>username</b></td>
<td><input type=text
name="username"></td> </tr>
<tr><td><B>password</b></td>
<td><input type=password
name="password"></td> </tr>
</table>
<input type=submit value="submit">
</form>
</body>
</html>

Deployment Descriptor
• How does the Container know which Servlet the client has requested for?

A Servlet can have 3 names


 
 Client known URL name
 
 Deployer known secret internal name

 
Actual file name

Web.xml file Web.xml file


<web-app>
<servlet> It is a deployment descriptor which is by default
<servlet-name> prog2</servlet-name> created by netbean, but in manual procedure we have
to create it. With respect to practical exam students
<servlet-class>Programs.prog2</servlet-class>
should write this file contents too. This file is
</servlet>
common for all servlet programs with only change in
<servlet-mapping>
servlet-name, url, class name as highlighted belo
<servlet-name> prog2</servlet-
name> <url-pattern>prog2</ url-
pattern > </servlet-mapping>
</web-app>
Output:

Submit from Prog2.html File Result from Prog2.java Servlet File

The javax.servlet.http Package

 The javax.servlet.http package contains a number of interfaces classes that are commonly used by
servlet developers. 

Interface Summary
HttpServlet

HttpServletRequest Extends the ServletRequest interface to provide


request information for HTTP servlets.

HttpServletResponse Extends the ServletResponse interface to provide HTTP-


specific functionality in sending a response.
Provides a way to identify a user across more than one page
HttpSession request or visit to a Web site and to store information about
that user.
doGet and doPost methods of Servlet

 The default service() method in an HTTP servlet routes the request to another method based
on the HTTP transfer method (POST, and GET). 

 HTTP POST requests from HTML file are routed to the doPost() method, HTTP GET
requests are routed to the doGet() method. 

 Most operations that involve forms use either a GET or a POST operation, so for most
servlets override either doGet() or doPost(). 

 Implementing both methods is a good practice to provide both input types or pass the request
object to a central processing method. 
Difference between HTTP doGet and HTTP doPost methods of Servlet

Difference Type GET (doGet()) POST (doPost())


HTTP Request The request contains only the Along with request line and header it
request line and HTTP header. also contains HTTP body.

URL Pattern Query string or form data is Form name-value pairs are sent in the
simply appended to the URL as body of the request, not in the URL
name-value pairs. itself.

Parameter passing The form elements are passed to The form elements are passed in the
the server by appending at the body of the HTTP request.
end of the URL.

Size The parameter data is limited Can send huge amount of data to the
(the limit depends on the server.
container normally 4kb)

Idempotency GET is Idempotent(can be POST is not idempotent(warns if applied


applied multiple times without multiple times without changing the
changing the result) result)

Usage Generally used to fetch some Generally used to process the sent data.
information from the host.

Security Not Safe - A person standing Safe - No one will be able to view what
over your shoulder can view data is getting submitted (Data hidden
your userid/pwd if submitted from users.)
via Get (Users can see data in
address bar.)
Data Format Supports ASCII. Supports ASCII + Binary.
Steps to make your Java Servlet Working:
1. Use the IDE Or notepad, for writing, debugging and compiling your servlet. Once you had
compiled your servlet successfully, a class file named MyServlet.class will be generated .
2. Copy the compiled MyServlet.class file generated to the following tomcat web server
directory

C:\tomcat\webapps\examples\web-inf\classes

3. Start the web server.


4. Open IE and type the following URL http://localhost:8080/examples/servlet/MyServlet

It should give the output Welcome to the World of Java Servlets on to the screen.

1) Program to accept user name and display a greeting message.

Solution:

Step1: We have to accept a user name from an HTML page. So create an HTML page as

follows using Notepad/Dos Edit or any HTML editor.

<html>

<head><title>Program 10a</title></head>

<body bgcolor=blue>

<form action="http://localhost:8080/examples/servlet/GreetingServlet " method="post">

<center><h3><font color=”red”>Enter Your Name</font> </h3>

<input type="text" name="name">

<br><br>

<input type="submit" value="Submit">

<input type="reset" value="Reset">

</center>

</form>

</body>

</html>

Step2: Save this file as say greeting.html in the following specified path of the tomcat web server
C:\tomcat\webapps\examples\servlets
Step3: Write the following servlet using Note pad/Dos Edit

import javax.servlet.*;

import javax.servlet.http.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContentType("text/html"); //set the type of the response
PrintWriter out=res.getWriter(); //getting hold of a handle to write into the output
// stream
String name = req.getParameter(“name”); // access the value entered in the text

// box named “name” &

// store it in a string variable name

out.println(“<html><title>Greeting Message</title></head>”); // prepare the

//response in html page

out.println(“<body bgcolor=wheat><h2>”);

out.println(“ Hello ”+name+”, How are you?”); // display a greeting message

out.println(“</h2></body></html>”); // end of html page

out.close(); // close the output stream

}
}
2) Program to change the background color of the page based on the color

selected by the user.

Solution: Here also our intention is to accept a color from the user and make it the background

Step1: We have to accept a color from an HTML page. So create an HTML page as

follows using Notepad/Dos Edit or any HTML editor.

<html>

<head><title>Program 10b</title></head>

<body bgcolor=blue>

<form action="http://localhost:8080/examples/servlet/ColorServlet" method="post">

<center><h3><font color=”red”>Enter Your Favourite Background Color</font> </h3>

<input type="text" name="color">

<br><br>

<input type="submit" value="Submit ">


<input type="reset" value="Reset">

</center>

</form>

</body>

</html>

Step3: Write the following servlet using Note pad/Dos Edit to process the request

import javax.servlet.*;

import javax.servlet.http.*;
import java.io.*;

public class ColorServlet extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContentType("text/html"); //set the type of the response
PrintWriter out=res.getWriter(); //getting hold of a handle to write into the output
// stream
String color = req.getParameter(“color”); // access the value entered in the text

//box named “color” &

// store it in a string variable color

out.println(“<html><body bgcolor = “+color+”></body></hml>”); // code to

//change the background color

out.close(); // close the output stream

}
}

3.Program to create and display cookie

Solution:

The program contains three files as summarized below:

File Description

AddCookie.html Allows a user to specify a name & value for the cookie

AddCookieServlet.java Processes the submission of AddCookie.html.

GetCookieServlet.java Displays cookie name & values.


Step1: Create the following html file that accepts the cookie name & value & save it as

say AddCookie.html in the tomcat servlets folder

<html>

<body>

<center>

<form method=”post” action=”http://localhost:8080/examples/servlet/AddCookiesServlet”>

<B> Enter the Name for Cookie:</B>

<input type=text name=”name” ><br><br>

Enter the value for a Cookie:

<input type=text name=”data” >

<input type=submit value=”submit”>

</form>

</body>

</html>

Step2: Create the following AddCookieServlet.java & save it in a temp folder

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException

String name=request.getParameter(“name”);

String data=request.getParameter(“data”);

Cookie cookie=new Cookie(name ,data);

response.addCookie(cookie);

response.setContentType(“text/html”);

PrintWriter pw= response.getWriter();

pw.println(“<B>MyCookie has been set to “);

pw.println( “<b>” + name + “ = ” + data);

pw.close();
}
}

Step 4: Create the following GetCookieServlet.java & save it in a temp folder

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class GetCookieServlet extends HttpServlet

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException

Cookie[] cookies=request.getCookies();

response.setContentType(“text/html”);

PrintWriter pw=response.getWriter();

pw.println(“<b>”);

for (int i=0;i<cookies.length;i++)

String name=cookies[i].getName();

String value=cookies[i].getValue();

pw.println(“Name=”+name + “Value= “ + value +”<br><br>”);

pw.close();

4. Program to create session and display session information viz, session ID, creation time and last
accessed.

Solution: This is another way to handle sessions. Here we try to get the current session first. If there is no
session currently, server will automatically create a session when you request. You request the session as

Program Steps:
Step 1: Create the following servlet using any text editor and save the file as, say

SessionServlet.java in a temporary folder, say C:\Lab

Note: the file name should match the class name

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//Get the HTTP Session object

HttpSession session = request.getSession(true);

//get the session id:

out.println("Session Id: " + session.getId()+"<br>");

// get the creation time:

out.println("Session Creation Time: " + session.getCreationTime()+"<br>");

// get the Last accessed time

out.println("Session Last Access Time: " + session.getLastAccessedTime());:

You might also like