0% found this document useful (0 votes)
15 views

Unit - II Servlet

Uploaded by

thirosul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit - II Servlet

Uploaded by

thirosul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CGI:=

1>standard for writing programs that can interact through a Web server with a client running a Web browser.
2>programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser.
3> middle man type interface thorough which web servers pass user’s requests to external databases and receive

the processed data to send it back to user.


BCA- III
4>run on the server and generate a response to return to the requesting client.
5> to generate dynamic content on web pages.
Unit - II
6>API for writing applications (often scripts) that can be run by a web server to service a particular range of URLs.
7>allows users to execute a program that resides in the server to process data and even access database in order to
produce the relevant content as shown in fig
Introducing Servlet

 Introduction to CGI:-
 The Common Gateway Interface (CGI) is a standard for writing programs that can
interact through a Web server with a client running a Web browser.
 These programs allow a Web developer to deliver dynamic information (usually in the
form of HTML) via the browser.
 Common Gateway Interface (CGI) is middle man type interface thorough which web
servers pass user’s requests to external databases/ information resources/ program
applications and receive the processed data to send it back to user.
 Common Gateway Interface (CGI) programs run on the server and generate a response
to return to the requesting client.
 CGI is a standard method used to generate dynamic content on web pages.
 CGI programs can be written in the C, C++, Java, and Perl languages, and as shell
scripts.
 It is an API for writing applications (often scripts) that can be run by a web server to
service a particular range of URLs.
 It allows users to execute a program that resides in the server to process data and
even access database in order to produce the relevant content as shown in fig.

 Introduction to Servlet :-


 Servlets are small programs that execute on the server side of a Web connection.
 Servlets are the Java programs that run on the Java-enabled web server or application
server.

INTRODUCTION TO THE SERVLET


Page 1 Prof. Patil R. M.
1. small programs that execute on the server side of a Web connection
2. run on the Java-enabled web server or application server.
 Servlets are nothing but the Java programs which reside on the server side and their
main purpose is to serve the client request.
 They are used to handle the request obtained from the webserver; process the request,
produce the response, then send a response back to the webserver.
 Servlet technology is used to create dynamic web pages on the server-side. It resides
in the server and gets invoked based on the request from client programs.
 Servlet technology is used to create Dynamic web application.
 As servlets are written in Java, they are platform independent, robust, and secured.
 In Servlets, a thread is created for each request unlike in CGI where a process is
created for each request. Hence, servlets give better performance than CGI.
1. The web container creates threads for handling the multiple requests to the servlet.
i> common memory share
 Advantages of Servlet Over CGI :-
ii> fast execution
iii>lightweight

There
iv>arelowmany advantages
cost of of Servlet over CGI. The web container creates threads for
commuication
handling the multiple requests to the servlet. Threads have a lot of benefits over the
Processes such as they share a common memory area, lighweight, cost of communication
between the threads are low. The basic benefits of servlet are as follows:
1. Platform Independence :-
INDP
Servlets are written entirely in java so these are platform independent. Servlets can run
on any Servlet enabled web server. For example if you develop an web application in
windows machine running Java web server, you can easily run the same on apache
web server (if Apache Serve is installed) without modification or compilation of code.
Platform independency of servlets provide a great advantages over alternatives of
servlets.

PERFOR 2. Performance :-
Servlet provide better performance that CGI in terms of processing time, memory
utilization because servlets uses benefits of multithreading and for each request a new
thread is created, that is faster than loading creating new Object for each request
with CGI.
EXTENS 3. Extensibility :-
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets
take all these advantages and can be extended from existing class to provide the ideal
solutions.
4. Safety :-
SAFTY
Java provides very good safety features like memory management, exception handling
etc. Servlets inherits all these features and emerged as a very powerful web server
extension.
SECURITY 5. Secure :-
Servlets are server side components, so it inherits the security provided by the web
server. Servlets are also benefited with Java Security Manager.

Page 2 Prof. Patil R. M.


 Difference between Java Servlets and CGI :-
PorShaComCosCook
Servlet CGI (Common Gateway Interface)

Portability Servlets are portable and efficient. CGI is not portable.

In Servlets, sharing data is


Sharing In CGI, sharing data is not possible.
possible.

Servlets can directly communicate CGI cannot directly communicate with


Comminication
with the webserver. the webserver.

Servlets are less expensive than


Cost CGI is more expensive than Servlets.
CGI.

Servlets can handle the cookies. CGI cannot handle the cookies.
Cookies handling

 Features of Servlet
Following are the main features of servlet:-
1. Portable:
Servlet uses Java as a programming language, Since java is platform independent,
the same holds true for servlets. For example, you can create a servlet on
Windows operating system that users GlassFish as web server and later run it on
any other operating system like Unix, Linux with Apache tomcat web server, this
feature makes servlet portable and this is the main advantage servlet has over
CGI.
2. Efficient and scalable:
Once a servlet is deployed and loaded on a web server, it can instantly start
fulfilling request of clients. The web server invokes servlet using a lightweight
thread so multiple client requests can be fulling by servlet at the same time using
the multithreading feature of Java. Compared to CGI where the server has to
initiate a new process for every client request, the servlet is truly efficient and
scalable.
3. Robust:
By inheriting the top features of Java (such as Garbage collection, Exception
handling, Java Security Manager etc.) the servlet is less prone to memory

Page 3 Prof. Patil R. M.


management issues and memory leaks. This makes development of web
application in servlets secure and less error prone.
4. Better performance: Because it creates a thread for each request not process
(like CGI).
5. Secure: Because it uses java language and java is a secure language. Java have
automatic garbage collection mechanism and a lack of pointers protect theservlets
from memory management problems.
6. Inexpensive There are number of free web servers available for personal use or
for commercial purpose. Mostly web server are very costly. So by using free web
server you can reduce project development price.
7. Extensibility The servlet API is designed in such a way that it can be easily
extensible. Servlets being written in Java, can be extended and polymorphed into
the objects that suits the user requirement.
8. Integration Servlets are tightly integrated with the server. Servlet can use the
server to translate the file paths, check authorization, perform logging andMIME
type mapping etc.
9. Persistent: Servlets remain in memory until explicitly destroyed. This helps in
serving several incoming requests. Servlets establishes connection only once with
the database and can handle several requests on the same database.
10. Server Independent: Servlets are compatible with any web server available
today.
11. Protocol Independent: Servlets can be created to support any protocols like FTP
commands, Telnet sessions, NNTP newsgroups, etc. It also provides extended
support for the functionality of HTTP protocol.
12. Fast: Since servlets are compiled into bytecodes, they can execute more quickly
as compared to other scripting languages. The bytecode compilation feature helps
servlets to give much better performance. In addition, it also provides advantage
of strong error and type checking.

 Servlet Architecture :-

Servlets perform the following major tasks:

Page 4 Prof. Patil R. M.


Step 1 : Client i.e. web browser sends the request to the web server.
Step 2 : Web server receives the request and sends it to the servlet container. Servlet
container is also called web container or servlet engine. It is responsible for handling
the life of a servlet.
Step 3 : Servlet container understands the request’s URL and calls the particular
servlet. Actually, it creates a thread for execution of that servlet. If there are multiple
requests for the same servlet, then for each request, one thread will be created.
Step 4 : Servlet processes the request object and prepares response object after
interacting with the database or performing any other operations and sends the response
object back to the web server
Step 5 : Then web server sends the response back to the client.

 Using Tomcat for Servlet Development :-


 To create servlets, you will need to download a servlet development environment.
 The one currently recommended by Sun is Tomcat 6.0, which supports the latest
servlet specification.
 Tomcat is an open-source product maintained by the Jakarta Project of the Apache
Software Foundation.
 It contains the class libraries, documentation, and run-time support that you will
need to create and test servlets.

 A Simple Servlet :-


To become familiar with the key servlet concepts, we will begin by building and testing
a simple servlet. The basic steps are the following:
1. Create and compile the servlet source code.
2. Start Tomcat.
3. Start a Web browser and request the servlet.
Let us examine each of these steps in detail.
1. Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
{

Page 5 Prof. Patil R. M.


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}

Let’s look closely at this program.


 First, note that it imports the javax.servlet package. This package contains the
classes and interfaces required to build servlets.
 Next, the program defines HelloServlet as a subclass of GenericServlet.
 The GenericServlet class provides functionality that makes it easy to handle
requests and responses.
 Inside HelloServet, the service( ) method (which is inherited from GenericServlet)
is overridden. This method handles requests from a client.
 Notice that the first argument is a ServletRequest object. This enables the servlet
to read data that is provided via the client request.
 The second argument is a ServletResponse object. This enables the servlet to
formulate a response for the client.
 The call to setContentType( ) establishes the MIME type of the HTTP response.
 In this program, the MIME type is text/html. This indicates that the browser should
interpret the content as HTML source code.
 Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream
is sent to the client as part of the HTTP response. Then println( ) is used to write
some simple HTML source code as the HTTP response.
 Compile this source code and place the HelloServlet.class file in the Tomcat class
files directory.
2. Start Tomcat
3. Start a Web Browser and Request the Servlet
Start a Web browser and enter the URL shown here:
http://localhost:8090/HelloServlet
Alternatively, you may enter the URL shown here:
http://192.168.0.1:9090/HelloServlet
This can be done because 192.168.0.1 is defined as the IP address of the local machine.
You will observe the output of the servlet in the browser display area. It will contain
the string Hello! in bold type.

Page 6 Prof. Patil R. M.


 Servlets APIs :-
Servlet API contains two java packages, are used to develop the servlet programs, they
are:
 javax.servlet(Basic)
 javax.servlet.http(Advance)
Various classes and interfaces present in these packages are:

Servlets Packages:
There are two types of packages in Java Servlet that are providing various functioning
features to servlet Applications. The two packages are as follows:
1. javax.servlet package
2. javax.servlet.http package

1. javax.servlet package :-
This package of Servlet contains many servlet interfaces and classes which are capacity
of handling any types of protocols And This javax.servlet package containing large
interfaces and classes that are invoked by the servlet or web server container as they are
not specified with any protocol.
Important Classes and Interfaces of javax.servlet package:

Interfaces Classes

Servlet GenericServlet

ServletConfig HttpConstraintElement

ServletContext HttpMethodConstraintElement

ServletContextListner MultipartConfigElement

ServletRegistration ServletContextEvent

ServletRequest ServletInputStream

ServletRequestListner ServletOutputStream

ServletResponse ServletRequestAttributeEvent

ServletCookieConfig ServletRequestEvent

SingleThreadModel ServletRequestEvent

Filter ServletRequestWrapper

Page 7 Prof. Patil R. M.


FilterConfig ServletResponseWrapper

FilterChain ServletSecurityElement

Interface Overview

Servlet This interface is used to create a servlet class. Each


servlet class must require to implement this interface
either directly or indirectly.

ServletRequest The object of this interface is used to retrieve the


information from the user.

ServletResponse The object of this interface is used to provide response


to the user.

ServletConfig ServletConfig object is used to provide the information


to the servlet class explicitly.

ServletContext The object of ServletContext is used to provide the


information to the web application explicitly.

Classes Overview

GenericServlet This is used to create servlet class. Internally, it


implements the Servlet interface.

ServletInputStream This class is used to read the binary data from user
requests.

ServletOutputStream This class is used to send binary data to the user side.

ServletException This class is used to handle the exceptions occur in


servlets.

ServletContextEvent If any changes are made in servlet context of web


application, this class notifies.

Page 8 Prof. Patil R. M.


2. javax.servlet.http package:
This package of servlet contains more interfaces and classes which are capable of
handling any specified http types of protocols on the servlet. This javax.servlet.http
package containing many interfaces and classes that are used for http requests only for
servlet
Important Classes and Interfaces of javax.servlet.http package:

Interfaces Classes

HttpServletRequest Cookie

HttpServletResponse HttpServlet

HttpSession HttpServletRequestWrapper

HttpSessionActivationListner HttpServletResponseWrapper

HttpSessionContext HttpSessionBindingEvent

HttpSessionAttributeListner HttpSessionEvent

HttpSessionIdListner HttpUtils

Interface Overview

HttpServletRequest The object of this interface is used to get the information from
the user under http protocol.

HttpServletResponse The object of this interface is used to provide the response of


the request under http protocol.

HttpSession This interface is used to track the information of users.

HttpSessionAttributeListener This interface notifies if any change occurs in HttpSession


attribute.

HttpSessionListener This interface notifies if any changes occur in HttpSession


lifecycle.

Some of the important interface of this package are listed below.

Class Overview

HttpServlet This class is used to create servlet class.

Page 9 Prof. Patil R. M.


Cookie This class is used to maintain the session of the state.

HttpSessionEvent This class notifies if any changes occur in the session of web
application.

HttpSessionBindingEvent This class notifies when any attribute is bound, unbound or


replaced in a session.

 The Life Cycle of a Servlet :-


Servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet-
1. The servlet is initialized by calling the init () method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
=======> web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.

first request for the servlet is received by the class loader


web container. ======>
web container calls the init
=====> method only once after creating
the servlet instance.

1. The init() method :


 The server basically invokes the init() method of servlet. This method is called only
when the servlet is loaded in the memory for the first time.
 The class loader is responsible to load the servlet class.
 The servlet class is loaded when the first request for the servlet is received by the
web container.

Page 10 Prof. Patil R. M.


 The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
 The web container calls the init method only once after creating the servlet instance.
The init() method is used to initialize the servlet.

The init() method definition looks like this:


Public void init()throwsServletException
servlet loaded when first request received by web
{
container by class loader=====>
// Initialization code... |
create instance of servlet created only once in life cycle
} |
2. The service() method : init() mehod called by servlet

webserver call  The service() method is the main method to perform the actual task.
service()  The servlet container (i.e. web server) calls the service() method to handlerequests
when request come coming from the client( browsers) and to write the formatted response back to the
client.
service() check http  Each time the server receives a request for a servlet, the server spawns a new
request type thread and calls service.
(GET,POST,PUT,
 The service() method checks the HTTP request type (GET, POST, PUT,
DELETE)
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
and call (doGET,
doPOST, appropriate.
doPUT, Here is the signature of this method:
doDELETE)
Public void service(ServletRequest request,ServletResponse
response) throws ServletException,IOException
{
//servlet code here
}
 The service () method is called by the container and service method invokes
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
 So you have nothing to do with service() method but you override either doGet()
or doPost() depending on what type of request you receive from the client.
 The doGet() and doPost() are most frequently used methods with in each service
request.

called once 3. The destroy() method :


servlet close db  The destroy() method is called only once at the end of the life cycle of a servlet.
halt bg thread  This method gives your servlet a chance to close database connections, halt
write cookies list & background threads, write cookie lists or hit counts to disk, and perform other such
hit count to the disk cleanup activities.
do cleanup
 After the destroy() method is called, the servlet object is marked for garbage
destroy() hold all collection.
servlet object to
GC
Page 11 Prof. Patil R. M.
 The destroy method definition looks like this:
public void destroy()
{
// Finalization code...
}

 Types of Servlet:-

The two main servlet types are, generic and HTTP.

1) Generic servlets:
o Extend javax.servlet.GenericServlet.
o Contain no inherent HTTP support or any other transport protocol, so that
protocol is independent.

2) HTTP servlets:
o Extend javax.servlet.HttpServlet.
o Contain built-in HTTP protocol support and are more useful in a Sun Java
System Web Server 7.0 environment.

1) GenericServlet Class :-
 GenericServlet implements the Servlet interface and provides an implementation
for all its method except the service() method.
 Hence it is abstract.
 GenericServlet class defines a protocol-independent(HTTP-less) servlet.
 Developing Servlet by extending GenericServlet is very easy because we have to
provide implementation only for the service() method.
 GenericServlet class is in javax.servlet package (javax.servlet.GenericServlet).
 service() method-
The prototype of service( ) method is :
public void service (ServletRequest req, ServletResponse resp) throws
ServletException,IOException

Page 12 Prof. Patil R. M.


 This method is automatically called by the server whenever a request for a
GenericServlet arrives. The service() method accepts two parameters:
1. A ServletRequestObject
2. A SerlvetResponseObject
The ServletRequest object allows reading data provided by the client request and the
ServletResponse object is used to send the response to the client.

Methods of GenericServlet class :-


There are many methods in GenericServlet class. They are as follows:
1. public void init (ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time
when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates
that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there
is no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the
given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined
in the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.

Program 1 :- Servlet “Hello World” example by extending GenericServlet class

index.html
We are creating an html file that would call the servlet once we click on the link on web page.
Create this file in WebContent folder. This path of the file should look like this:
WebContent/index.html

<!DOCTYPE html>
<html>
<head>

Page 13 Prof. Patil R. M.


<meta charset="UTF-8">
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="HelloWorld">Click to call Servlet</a>
</body>
</html>

Now, we are creating a Generic Servlet by extending GenericServlet class. When creating a
GenericServlet you should always override service() method.

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

public class MyFirstServlet extends GenericServlet

{
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("Hello Servlet");

pw.close();
}
}

Program 2 :- Creating the Servlet class by extending GenericServlet


We are creating a Servlet extending the GenericServlet abstract class. GenericServlet class
implements Servlet and ServletConfig interface. A Servlet class is just a regular Java class
which ends with a .java extension, hence we have named this file MyServlet1.java.

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

public class MyServlet1 extends GenericServlet


{

Page 14 Prof. Patil R. M.


public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello there!");
out.println("Hello from the Servlet made by extending
GenericServlet abstract class.");
System.out.println("Putting the Servlet in service");
}

Program 3 :-

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

public class First extends GenericServlet {


public void service(ServletRequest req, ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

2) HttpServlet Class :-
 The HttpServlet class extends the GenericServlet class and implements Serializable
interface.

 It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Page 15 Prof. Patil R. M.


 The most important are the different doxxx methods that get called when a related
HTTP request method is used.

 The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace.

 Each method is invoked when a corresponding HTTP method is used.

 For instance, the doGet method is invoked when the servlet receives an a HTTP request
that was send using the GET method.

 Among these methods, the doPost and doGet methods are the most frequently used.

Methods in HttpServlet :-
The methods in httpservlet are given as follows:
1. protected void doDelete (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a DELETE
request. The DELETE operation allows a client to remove a document or web page from
the server.
2. protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method)”to allow a servlet to handle a GET request.
Overriding this method to support a GETrequest also automatically supports an HTTP
HEAD request.
3. protected void doHead(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
Receives an HTTP HEAD request from the protected service method and handles the
request.
4. protected void doOptions(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle OPTIONS
request. The OPTIONS request determines which HTTP methods the server supports and
returns an appropriate header.
5. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a POST request.
The HTTP POST method allows the client to send data of unlimited length to the Web
server a single time and is useful when posting information such as credit card numbers.
6. protected void doPut(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException
Called by the server (via the service method) to allow a servlet to handle a PUT request.
The PUT operation allows a client to place a file on the server and is similar to sending a
file by FTP.
7. protected void doTrace(HttpServletRequest req,HttpServletResponse resp) throws
ServletException, IOException

Page 16 Prof. Patil R. M.


Called by the server (via the service method) to allow a servlet to handle a TRACE request.
ATRACE returns the headers sent with the TRACE request to the client, so that they can
be used in debugging. There’s no need to override this method.
8. protected long getLastModified(HttpServletRequest req)
Returns the time the HttpServletRequest object was last modified, in milliseconds since
midnight 1January 1970GMT.If the time is unknown, this method returns a negative
number (the default).
9. protected void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
Receives standard HTTP requests from the public service method and dispatches them to
the doXXX methods defined in this class. This method is an HTTP· specific version of
the service method. There’s no need to override this method.
10. public void service (ServletRequest req/ ServletRespon,se res) throws
ServletException, IOException
Dispatches client request to the protected service method. There’s no need to override this
method.

Program 1:-

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

// here FirstServlet class inherit HttpServlet


public class FirstServlet extends HttpServlet {

// we are defining the doGet method of HttpServlet


// abstract class
public void doGet(HttpServletRequest
request,HttpServletResponse response)
{
// here user write code to handle doGet request
PrintWriter out = response.getWriter();
Out.println(“<h1> Hello World </h1>”)
}

} // class ends

Program 2:-

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{

Page 17 Prof. Patil R. M.


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

 Directory Structure of Servlet files :-

The diagram above depicts how to arrange the Servlet files in a specific directory
structure, as per Java Servlet Specification-
 Project Folder - We have created a new folder for this project named GenericServ
within the Tomcat webapps folder, which contains our Servlet class(.java) file.
 WEB-INF - This folder should contain the deployment descriptor file(web.xml) of
your Java Servlet program.
 classes - This folder should contain the compiled(.class) form of your Java Servlet
class.

Page 18 Prof. Patil R. M.


 Handling HTTP Requests and Responses
 The HttpServlet class provides specialized methods that handle the various types of
HTTP requests.
 A servlet developer typically overrides one of these methods. These methods are
doDelete() , doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
 However, the GET and POST requests are commonly used when handling form
input.

Handling HTTP GET Requests


 Here we will develop a servlet that handles an HTTP GET request.
 The servlet is invoked when a form on a Web page is submitted.
 The example contains two files. A Web page is defined in ColorGet.htm and a servlet is
defined in ColorGetServlet.java.
 The HTML source code for ColorGet.htm is shown in the following listing. It defines a
form that contains a select element and a submit button.
 Notice that the action parameter of the form tag specifies a URL. The URL identifies a
servlet to process the HTTP GET request.

<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examp*les/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for ColorGetServlet.java is shown in the following listing. The
doGet() method is overridden to process any HTTP GET requests that are sent to this

Page 19 Prof. Patil R. M.


servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection
that was made by the user. A response is then formulated.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

Compile the servlet and perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the Web page in a browser.
3. Select a color.
4. Submit the Web page.

After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL
that is sent to the Web server. Assume that the user selects the red option and submits the
form.

Handling HTTP POST Requests


 Here we will develop a servlet that handles an HTTP POST request.
 The servlet is invoked when a form on a Web page is submitted.

Page 20 Prof. Patil R. M.


 The example contains two files. A Web page is defined in ColorPost.htm and a servlet
is defined in ColorPostServlet.java.
 The HTML source code for ColorPost.htm is shown in the following listing. It is
identical to ColorGet.htm except that the method parameter for the form tag explicitly
specifies that the POST method should be used, and the action parameter for the form
tag specifies a different servlet.

<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The
doPost( ) method is overridden to process any HTTP POST requests that are sent to this
servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection
that was made by the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");

Page 21 Prof. Patil R. M.


PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

Compile the servlet and perform the same steps as described in the previous section to
test it.

 Get vs. Post


There are many differences between the Get and Post request. Let's see these
differences:

GET POST

1) In case of Get request, only In case of post request, large amount


AMT DATA
limited amount of data can be sent of data can be sent because data is
because data is sent in header. sent in body.

2) Get request is notsecured Post request is secured because data


SECURITY because data is exposed in URL bar. is not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be


BOOKMARK
bookmarked.

4) Get request is idempotent . It Post request is non-idempotent.


INDEMPOTENT
means second request will be ignored
until response of first request is
delivered

5) Get request is more efficient and Post request is less efficient and
EFFICIENCY
used more than Post. used less than get.

Page 22 Prof. Patil R. M.


 Servlet – RequestDispatcher :-
 The RequestDispatcher is an Interface that comes under package javax.servlet.
 Using this interface we get an object in servlet after receiving the request.
 Using the RequestDispatcher object we send a request to other resources which include
(servlet, HTML file, or JSP file).
 A RequestDispatcher object can be used to forward a request to the resource or to
include the resource in a response. RequestDispatcher:-
1.Interface that comes under package javax.servlet.
 The resource can be dynamic or static. 2.Using this interface we get an object in servlet after receiving the request
3.RequestDispatcher object we send a request to other resources which include (servlet,
HTML file, or JSP file).
4.RequestDispatcher object can be used to forward a request to the resource or to
include the resource in a response.
Methods of RequestDispatcher Interface :-
The class contains two methods:
1. forward Methods of RequestDispatcher Interface :-
1. forward
2. include 2. include

1) Forword () Method:-
 Forwards a request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
 The response of second servlet is sent to the client. Response of the first servlet is
not displayed to the user.
1) Forword () Method:-
1.Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2.The response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.

public void forward(ServletRequest request,ServletResponse response)


throws ServletException,java.io.IOException

Page 23 Prof. Patil R. M.


 The method get called before the response has been sent to the client. If the response
is already sent then the method will throws an IllegalStateException.
 The parameter request(HttpServletRequest type) and
response(HttpServletResponse type) are the same objects as were passed to the
calling servlet’s service method.

Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
// Perform all the work as per your
// application's architecture
try {
RequestDispatcher requestDispatcher;
// path is a string specifying the pathname to
// the resource. If it is relative, it must be
// relative against the current servlet
requestDispatcher = request.getRequestDispatcher("path");
requestDispatcher.forward(request, response);
}
catch (ServletException servletException) {
}
catch (IOException ioException) {
}
catch (IllegalStateException illegalStateException) {
}
}

2) Include () Method:-
 Includes the content of a resource (servlet, JSP page, or HTML file) in theresponse.

Page 24 Prof. Patil R. M.


2) Include () Method:-
1. Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
2.Response of second servlet is included in the response of the first servlet that is being sent to the client.

 Response of second servlet is included in the response of the first servlet that is
being sent to the client.

public void include(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException

 The parameter request (HttpServletRequest type) and


response(HttpServletResponse type) are the same objects as were passed to the
calling servlet’s service method.
 This method sets the dispatcher type of the given request to
DispatcherType.INCLUDE.

Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
// Perform all the work as
// per your application's architecture
try {
RequestDispatcher requestDispatcher;
// path is a string specifying the pathname to

Page 25 Prof. Patil R. M.


// the resource. If it is relative, it must be
// relative against the current servlet
requestDispatcher=request.getRequestDispatcher("path");
requestDispatcher.include(request, response);
}
catch (ServletException servletException) {
}
catch (IOException ioException) {

}
}
}

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is Paniv, it
will forward the request to the WelcomeServlet, otherwise will show an error message: sorry
username or password error.
 index.html file: for getting input from the user.
 Login.java file: a servlet class for processing the response. If password is Paniv, it
will forward the request to the welcome servlet.
 WelcomeServlet.java file: a servlet class for displaying the welcome message.
 web.xml file: a deployment descriptor file that contains the information about the
servlet.

Page 26 Prof. Patil R. M.


index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>

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

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
String p=request.getParameter("userPass");

if(p.equals("Paniv"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);

Page 27 Prof. Patil R. M.


}

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

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
}

web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>

Page 28 Prof. Patil R. M.


<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Output:-
When Entering User name or password incorrect.

Page 29 Prof. Patil R. M.


Welcome screen on entering correct user name and password:

1> java program run on java enabled web server


2> client request==> process request==> response to the client
3> HTTP stateless protocol.each request client establish new connection with new request .there isno track
4>session simply particular interval of time
5> conversation of user period of time known as session in gernal it refer certain period of time
6> recording object in the session in session in called tracking

 Servlet – Session Tracking :-


 Servlets are the Java programs that run on the Java-enabled web server or application
server.
 They are used to handle the request obtained from the web server, process the request,
produce the response, then send a response back to the webserver.
 HTTP is a “stateless” protocol, which means that each time a client requests a
Web page, the client establishes a new connection with the Web server, and the server
does not retain track of prior requests.
 Session simply means a particular interval of time.
 It is also known as session management in servlet.
 The conversation of a user over a period of time is referred to as a session. In general,
it refers to a certain period of time.

Page 30 Prof. Patil R. M.


7> some applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server.
8>Session tracking is the process of remembering and documenting customer conversions over time.
Session management is another name for it.
 The recording
9> “stateful web application” refersoftothe object
a web in session that
application is known as tracking.
is capable of
remembering and  recording client conversions over time.
However, in some applications, it is necessary to save state information so that
10> session can be created via the
information cangetSession(
be collected) from
method of HttpServletRequest.
several interactions between An
a browser and a
HttpSession object is returned
server.
11> object can store a set of bindings that associate names with objects. The
setAttribute( ),getAttribute(
Sessions provide such a mechanism.), and removeAttribute( ) methods
), getAttributeNames(
of HttpSession manage
Sessionthese bindings.
tracking is the process of remembering and documenting customer
conversions over time. Session management is another name for it.
 The term “stateful web application” refers to a web application that is capable of
remembering and recording client conversions over time.
 A session can be created via the getSession( ) method of HttpServletRequest. An
HttpSession object is returned.
 This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods
of HttpSession manage these bindings.
 It is important to note that session state is shared among all the servlets that are
associated with a particular client. WHY WE NEED SESSION TRACKING
1> to make the client-server relationship stateful.
2> for tracking conversions in online shopping, mailing
applications, and E-Commerce applications.
3>HTTP protocol is stateless, which implies that each request is
Why is Session Tracking Required?treated as a new one
 Because the HTTP protocol is stateless, we require Session Tracking to make the client-
server relationship stateful. 
 Session tracking is important for tracking conversions in online shopping, mailing
applications, and E-Commerce applications.
 The HTTP protocol is stateless, which implies that each request is treated as a new one.
As you can see in the image below.

Session Tracking Techniques :-


Session Tracking employs Four Different techniques
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

A. Cookies
Cookies are little pieces of data delivered by the web server in the response header and kept
by the browser. Each web client can be assigned a unique session ID by a web server.
Cookies are used to keep the session going. Cookies can be turned off by the client.

1> little pieces of data delivered by the web server in the response header and kept by the browser
2> Each web client can be assigned a unique session ID by a web server.
3>used to keep the session going
4>Cookies can be turned off by the client.

Page 31 Prof. Patil R. M.


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1> info inserted into the web pages (HIDDEN FROM USER FIELD)
via the hidden form field =====================================>2>then transferred to the server
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is then
transferred to the server. These fields are hidden from the user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >
URL writing
1> each request and return, append some more data via URL as request parameters
C. URL Rewriting 2> keep session management and browser operations in sync.

With each request and return, append some more data via URL as request parameters. URL
rewriting is a better technique to keep session management and browser operations in sync.

D. HttpSession
A user session is represented by the HttpSession object. A session is established between an
HTTP client and an HTTP server using the HttpSession interface. A user session is a
collection
1> small piece of data about
of information as a atext
userfile
that spans on
stored many HTTPmachine
client’s requests.by a web application.
2> kept for various information tracking purpose.
3> Servlets transparently supports HTTP cookies

4> HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every
1) Cookies :-
new request
5> case of cookie
 A a cookie
text fileiswith small
a small piece
piece of information
of information is added
as a text to the
file stored onresponse of first by
client’s machine request.
a
6> when a new request comes
web application. cookie is by default added with the request
7> With this information we can identify that it is a new user or a previous user.
 Cookies are text files stored on the client computer and they are kept for various
information tracking purpose.
 Java Servlets transparently supports HTTP cookies.
 As HTTP is a stateless protocol so there is no way to identify that it is a new user or
previous user for every new request.
 In case of cookie a text file with small piece of information is added to the response of
first request.
 They are stored on client’s machine.
 Now when a new request comes cookie is by default added with the request.
 With this information we can identify that it is a new user or a previous user.

Cookie working mechanism - how cookies work?


 It is one of the state management techniques in session tracking.
 Basically, the server treats every client request as a new one so to avoid this situation
cookies are used.
 When the client generates a request, the server gives the response with cookies having
an id which are then stored in the client’s browser.
 Thus if the client generates a second request, a cookie with the matched id is also sent
to the server.
WORKING MECHANISM:=
1> state management techniques in session tracking.
2>server treats every client request as a new one so to avoid this situation cookies are used.
3>client generates a request, the server gives the response with cookies having an id which are then stored in the client’s
browser. Page 32 Prof. Patil R. M.
4> if the client generates a second request, a cookie with the matched id is also sent to the server
 The server will fetch the cookie id, if found it will treat it as an old request otherwise
the request is considered new.

Types of cookies:
1. Session cookies/Non-persistent cookies: These types of cookies are session
dependent i.e. they are accessible as long as session is open and they are lost when
session is closed by exiting from the web application.
2. Permanent cookies/Persistent cookies: These types of cookies are session
independent i.e. they are not lost when session is closed by exiting from the web
application. They are lost when they expire.

Cookie class :-
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot
of useful methods for cookies.

Constructor of Cookie class:-

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified name and


value) value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Page 33 Prof. Patil R. M.


1> Public void set (String name, string value)=======> public void setMaxAge(int
expiry) ==========> max age of
Name, Value cookies
public String get Value()===========================>

Method Description

public void setMaxAge(int Sets the maximum age of the cookie in


expiry) seconds.

public String getName() Returns the name of the cookie. The name
cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String Changes the name of the cookie.


name)

public void setValue(String Changes the value of the cookie.


value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other inter
They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add coo
response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the c
from the browser. METHOD REQUIRED FOR COOKIES:-
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add coo
response object.
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add coo
response object.
How to create Cookie?
Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal"); //creating cookie object
response.addCookie(ck); //adding cookie in the response
HOW TO CREATE COOKIES:-
COOKIE CK=NEW COOKIE("USE","JAISWAL");
RESPONSE.ADDCOOKIE(CK);
How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user",""); //deleting value of cookie
ck.setMaxAge(0); //changing the maximum age to 0 seconds HOW TO DELETE COOKIE:-
Cookie ck=new Cookie("user",""); //deleting value
response.addCookie(ck); //adding cookie in the response of cookie
ck.setMaxAge(0); //changing the maximum age to
0 seconds
response.addCookie(ck); //adding cookie in the
response

Page 34 Prof. Patil R. M.


ADVANTAGES:-\
1.Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Advantages of cookies:
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
DISADVANTAGES:-
1. if cookie is disabled from the browser.
Disadvantages of cookies: 2.Only textual information
3.SEQURITY RISK

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.
3. Security risk is there because cookies exist as a text file so any one can open and read
user’s information.

Simple example of Servlet Cookies :-


In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

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

public class FirstServlet extends HttpServlet {

Page 35 Prof. Patil R. M.


public void doPost(HttpServletRequest request, HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}

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

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

Page 36 Prof. Patil R. M.


out.close();

}catch(Exception e){System.out.println(e);}
}

web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

Page 37 Prof. Patil R. M.


Output

Page 38 Prof. Patil R. M.


1>a hidden (invisible) textfield
2>store the information in the hidden field and get it from another servlet.
3>approach is better if we have to submit form in all the pages and we don't want to depend on the browser
4>we store the information in the hidden field and get it from another
servlet.

SYNTAX-<input type="hidden" name="Paniv" value="SIIT">


2) Hidden Form Field:-
 In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of a user.
 In such case, we store the information in the hidden field and get it from another
servlet.
 This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.
 In such case, we store the information in the hidden field and get it from another
servlet.
 This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.
Let's see the code to store value in hidden field.
<input type="hidden" name="Paniv" value="SIIT">

Here, Paniv is the hidden field name and SIIT is the hidden field value.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not. ADVANTAGES:-
always work whether cookie is disabled or not
2. All browsers support hidden fields. browsers support hidden fields.

Disadvantage of Hidden Form Field:


1. It is maintained at server side. DISADVANTAGES:-
maintained at server side.
2. Extra form submission is required on each pages. Extra form submission is required on each pages.
Only textual information can be used.
3. Only textual information can be used.

Example of using Hidden Form Field


In this example, we are storing the name of the user in a hidden textfield and getting that
value from another servlet.

Page 39 Prof. Patil R. M.


In this method we are transferring the client detail from firstServlet to Second Servlet

Index.html
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="Post">
<!-- Move the control to firstServlet -->
Name:<input type="text" name="userName" /><br />
<input type="submit" value="submit" />
</form>
</body>
</html>

Output

FirstServlet.java
// Java program to demonstrate
// Hidden form field method

package GeeksforGeeks;

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

@WebServlet("/FirstServlet")

// this annotation is used for replacing xml file


public class FirstServlet extends HttpServlet {

// class name is FirstServlet which extends HttpServlet


public void doPost(HttpServletRequest request,
HttpServletResponse response)
{

Page 40 Prof. Patil R. M.


try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String username =
request.getParameter("userName");
out.print("Welcome " + username);
out.print("<form action='SecondServlet'>");
out.print("<input type='hidden' name='username' value='"
+ username + "'>");
out.print("<input type='submit' value='submit'>");
out.print("</form>");
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}

Output

SecondServlet
// Java program to demonstrate
// Hidden form field method

package GeeksforGeeks;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet; // Importing annotation
import javax.servlet.http.*;

// using this annotation we dont need


// xml file for dispathing servlet
@WebServlet("/SecondServlet")

Page 41 Prof. Patil R. M.


public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
{
try {
response.setContentType("text/html");

PrintWriter out = response.getWriter();

// getting value from the query string


String username = request.getParameter("username");

// taking the value of username from First servlet using


getparameter object
out.print("WELCOME " + username);

// out.println is used to print on the client web


browser
out.close();
}

catch (Exception e) {
System.out.println(e);
}
}
}

Output

3) URL Rewriting :-
 URL rewriting is the process of modifying Uniform Resource Locators (URLs) for
various purposes.
 The URL as a “web address” is a string that, when entered into the browser bar field,
directs the browser to move to a given site and page.
 Changing the URL can help with user access and site visibility; it can also be used by
hackers to redirect users without their knowledge or “trap” them in a certain site.

Page 42 Prof. Patil R. M.


1>modifying Uniform Resource Locators (URLs) for various purposes
2>“web address” is a string that, when entered into the browser bar field, directs the browser to move to a given site and page.
3>Changing the URL can help with user access and site visibility used by hackers to redirect users without their knowledge or “trap” them in a
certain site
4>way of appending data at the end of URL. Data is appended in name value pair form. Multiple parameters can be appended in one URL with name value pairs.
5>send parameter name/value pairs using the following format

SYNTAX-  URL rewriting is a way of appending data at the end of URL. Data is appended in name
url?name1=value1&name2=value2&??
<<DESCRIBE IT >> value pair form. Multiple parameters can be appended in one URL with name value
pairs.
 We can send parameter name/value pairs using the following format:

Syntax:
url?name1=value1&name2=value2&??

 A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&).
 When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
 From a Servlet, we can use getParameter() method to obtain a parameter value.

How to get parameter value from url in servlet?


HttpServletRequest interface’s getParameter() method is used to get parameter value from url
in servlet. GET PARAMETER VALUE FROM URL
used to get parameter value from url in servlet.
Syntax: String value = request.getParameter(“fieldName”);

String value = request.getParameter(“fieldName”);

Advantage of URL Rewriting :-


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.
ADVANTAGES:-
1> always work whether cookie is disabled or not (browser independent).
2>submission is not required on each pages.
Disadvantage of URL Rewriting :-
1. It will work only with links. DISADVANTAGES:-
work only with links.
2. It can send Only textual information. Only textual information

Example of using URL Rewriting

In this example, we are maintaining the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query string
in another page.

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Page 43 Prof. Patil R. M.


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

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();
}catch(Exception e){System.out.println(e);}
}
}

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

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Page 44 Prof. Patil R. M.


//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();

}catch(Exception e){System.out.println(e);}
}
}

web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

Page 45 Prof. Patil R. M.


HTTP SESSION:-
1> interface that provides a way to identify a user in multiple page requests.
2>A unique session id is given to the user when first request comes stored in a request parameter or in a cookie.

4) HttpSession:-
 HttpSession is an interface that provides a way to identify a user in multiple page
requests.
 A unique session id is given to the user when first request comes. This id is stored in
a request parameter or in a cookie.

HOW TO GET GET SESSION OBJ:-


How to get session object? HttpSession session = request.getSession();

HttpServletRequest interface’s getSession() method is used to get the session object.


Syntax:
HttpSession session = request.getSession();

How to set attribute in session object?


HttpSession interface’s setAttribute() method is used to set attribute in session object.
Syntax:
public void setAttribute(String name,Object value);
HOW TO SET SESSION ATTRIBUTE:-
public void setAttribute(String name,Object value);
Example:
session.setAttribute("attName", "attValue");

How to get attribute from session object?


HttpSession interface’s getAttribute() method is used to get attribute from session object.
Syntax:
public Object getAttribute(String name);
HOW TO GET ATTRIBUTE FROM SESSION:-
Example: String value = (String) session.getAttribute("attName");

String value = (String) session.getAttribute("attName");

Methods in HttpSession Interface :-


Method Description

Gets the HttpSession object. If the request doesn’t


public HttpSession getSession() have a session associated with it, a new session is
created.

Gets the session associated with the request. If not


public HttpSession already present, then a new one is created based
getSession(boolean create) on the value of the boolean argument passed into
it.

Page 46 Prof. Patil R. M.


public String getId() Returns the unique session id.

It returns the time when this session was created,


public long getCreationTime() measured in milliseconds since midnight January
1, 1970 GMT.

It returns the time when this session was last


public long
accessed, measured in milliseconds since
getLastAccessedTime()
midnight January 1, 1970 GMT.

It returns the time when this session was last


public long
accessed, measured in milliseconds since
getLastAccessedTime()
midnight January 1, 1970 GMT.

public void invalidate() Invalidates the session.

1>Any kind of object can be stored into a session, be it a text, database, dataset etc.
2>Usage of sessions is not dependent on the client’s browser.
3>
Advantages of Http Sessions in Servlet
 Any kind of object can be stored into a session, be it a text, database, dataset etc.
 Usage of sessions is not dependent on the client’s browser.
 Sessions are secure and transparent.

1>Performance overhead due to session object being stored on server.


Disadvantages of Http session 2>
 Performance overhead due to session object being stored on server.
 Overhead due to serialization and de-serialization of data.

Example of Session tracking using HttpServlet Interface:


In the below example the setAttribute() and getAttribute() methods of the HttpServlet class
is used to create an attribute in the session scope of one servlet and fetch that attribute from
the session scope of another servlet.

index.html

<html>
<head>
<body>
<form action="servlet1">

Page 47 Prof. Patil R. M.


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

First.java

// The first servlet


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

< div class


= "noIdeBtnDiv" > public class First extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
{
try { /*Declaration of the get method*/

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n = request.getParameter("userName");
/*Fetching the contents of the userName field from the
form*/
out.print("Welcome " + n); // Printing the username

HttpSession session = request.getSession();


/* Creating a new session*/

session.setAttribute("uname", n);

out.print("<a href='servlet2'>visit</a>");
// Link to the second servlet

out.close();
}

catch (Exception e) {
System.out.println(e);
}
}
}

Page 48 Prof. Patil R. M.


Second.java

// The second servlet


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

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response) try {
/*Declaration of the get method*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(false);

String n = (String)session.getAttribute("uname");
out.print("Hello " + n);

out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}

web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>Second</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

Page 49 Prof. Patil R. M.


Output:

 index.html :

 Servlet1 :

 Servlet2 :

Page 50 Prof. Patil R. M.

You might also like