What Is A Servlet?

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

SERVLET

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to
the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.
What is a web application?
A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements such
as HTML, CSS, and JavaScript. The web components typically execute in Web Server
and respond to the HTTP request.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request,
it starts a new process.

Disadvantages of CGI
There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits over
the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as
follows:

1. Better performance: because it creates a thread for each request, not


process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

HTTP (Hyper Text Transfer Protocol)


The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol
used to establish communication between client and server.

HTTP is TCP/IP based communication protocol, which is used to deliver the data like
image files, query results, HTML files etc on the World Wide Web (WWW) with the
default port is TCP 80. It provides the standardized way for computers to
communicate with each other.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially
interesting information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which
includes following information:

o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header

The HTTP request method indicates the method to be performed on the resource
identified by the Requested URI (Uniform Resource Identifier). This method is
case-sensitive and should be used in uppercase.

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 limited In case of post request, large amount
amount of data can be sent because data of data can be sent because data is
is sent in header. sent in body.

2) Get request is not secured because data Post request is secured because data
is exposed in URL bar. is not exposed in URL bar.

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

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


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

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

GET and POST


Two common methods for the request-response between a server and client are:

o GET- It requests the data from a specified resource


o POST- It submits the processed data to a specified resource

Anatomy of Get Request


The query string (name/value pairs) is sent inside the URL of a GET request:

1. GET/RegisterDao.jsp?name1=value1&name2=value2

As we know that data is sent in request header in case of get request. It is the default
request type. Let's see what information is sent to the server.

Some other features of GET requests are:


o It remains in the browser history
o It can be bookmarked
o It can be cached
o It have length restrictions
o It should never be used when dealing with sensitive data
o It should only be used for retrieving the data

Anatomy of Post Request


The query string (name/value pairs) is sent in HTTP message body for a POST
request:

POST/RegisterDao.jsp HTTP/1.1
Host: www. javatpoint.com
name1=value1&name2=value2

As we know, in case of post request original data is sent in message body. Let's see
how information is passed to the server in case of post request.

Some other features of POST requests are:

o This requests cannot be bookmarked


o This requests have no restrictions on length of data
o This requests are never cached
o This requests do not retain in the browser history

Servlet Container
It provides the runtime environment for JavaEE (j2ee) applications. The client/user
can request only a static WebPages from the server. If the user wants to read the web
pages as per input then the servlet container is used in java.

The servlet container is the part of web server which can be run in a separate
process. We can classify the servlet container states in three types:
The servlet container is the part of web server which can be run in a separate
process. We can classify the servlet container states in three types:

o Standalone: It is typical Java-based servers in which the servlet container and


the web servers are the integral part of a single program. For example:-
Tomcat running by itself
o In-process: It is separated from the web server, because a different program
runs within the address space of the main server as a plug-in. For example:-
Tomcat running inside the JBoss.
o Out-of-process: The web server and servlet container are different programs
which are run in a different process. For performing the communications
between them, web server uses the plug-in provided by the servlet container.

The Servlet Container performs many operations that are given below:

o Life Cycle Management


o Multithreaded support
o Object Pooling
o Security etc.

Server: Web vs. Application


Server is a device or a computer program that accepts and responds to the request
made by other program, known as client. It is used to manage the network resources
and for running the program or software that provides services.

There are two types of servers:


1. Web Server
2. Application Server

Web Server

Web server contains only web or servlet container. It can be used for servlet, jsp,
struts, jsf etc. It can't be used for EJB.

It is a computer where the web content can be stored. In general web server can be
used to host the web sites but there also used some other web servers also such as
FTP, email, storage, gaming etc.

Examples of Web Servers are: Apache Tomcat and Resin.

Web Server Working


It can respond to the client request in either of the following two possible ways:

o Generating response by using the script and communicating with database.


o Sending file to the client associated with the requested URL.

The block diagram representation of Web Server is shown below:


Important points

o If the requested web page at the client side is not found, then web server will
sends the HTTP response: Error 404 Not found.
o When the web server searching the requested page if requested page is found
then it will send to the client with an HTTP response.
o If the client requests some other resources then web server will contact to
application server and data is store for constructing the HTTP response.

Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp,
struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a
server centric architecture.

It provides the middleware services for state maintenance and security, along with
persistence and data access. It is a type of server designed to install, operate and
host associated services and applications for the IT services, end users and
organizations.

The block diagram representation of Application Server is shown below:


The Example of Application Servers are:

1. JBoss: Open-source server from JBoss community.


2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic: Provided by Oracle. It more secured.
4. Websphere: Provided by IBM.

Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.

The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10.FilterChain
11.ServletRequestListener
12.ServletRequestAttributeListener
13.ServletContextListener
14.ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10.ServletException
11.UnavailableException

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface
defines methods that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life
cycle methods of servlet. These are invoked by the web container.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.

public void service(ServletRequest provides response for the incoming


request,ServletResponse response) request. It is invoked at each request by
the web container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.

public ServletConfig returns the object of ServletConfig.


getServletConfig()

public String getServletInfo() returns information about servlet such


as writer, copyright, version etc.

Servlet Example by implementing Servlet interface


Let's see the simple example of servlet by implementing the servlet interface.

File: First.java
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

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 simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready
state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state

1) Servlet class is loaded


The classloader 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.

2) Servlet instance is created


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.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The
init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is
given below:

public void destroy()

Steps to create a servlet example


There are given 6 steps to create a servlet example. These steps are required for all
the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http


request specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as
follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
2)Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.

DemoServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
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


}}
Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the
information about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There
are many xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements
to run the simple servlet program.

web.xml file

<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

Description of the elements of web.xml file


There are too many elements in the web.xml file. Here is the illustration of some
elements that is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.


<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the

servlet.

How Servlet works?


It is important to learn how servlet works for understanding the servlet well. Here, we
are going to get the internal detail about the first servlet program.

The server checks if the servlet is requested for the first time.

If yes, web container does the following tasks:

o loads the servlet class.


o instantiates the servlet class.
o calls the init method passing the ServletConfig object

else

o calls the service method passing request and response objects

The web container calls the destroy method when it needs to remove the servlet such
as at time of stopping server or undeploying the project.

How web container handles the servlet request?


The web container is responsible to handle the request. Let's see how it handles the
request.

o maps the request with the servlet in the web.xml file.


o creates request and response objects for this request
o calls the service method on the thread
o The public service method internally calls the protected service method
o The protected service method calls the doGet method depending on the type of
request.
o The doGet method generates the response and it is passed to the client.
o After sending the response, the web container deletes the request and
response objects. The thread is contained in the thread pool or deleted depends
on the server implementation.

What is written inside the public service method?


The public service method converts the ServletRequest object into the
HttpServletRequest type and ServletResponse object into the HttpServletResponse
type. Then, calls the service method passing these objects. Let's see the internal
code:

public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try
{
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a
servlet such as content type, content length, parameter names and values, header
informations, attributes etc.

Methods of ServletRequest interface


There are many methods defined in the ServletRequest interface. Some of them are
as follows:

Method Description

public String getParameter(String is used to obtain the value of a


name) parameter by name.

public String[] returns an array of String containing all


getParameterValues(String name) values of given parameter name. It is
mainly used to obtain values of a Multi
select list box.

java.util.Enumeration returns an enumeration of all of the


getParameterNames() request parameter names.

public int getContentLength() Returns the size of the request entity


data, or -1 if not known.

public String Returns the character set encoding for


getCharacterEncoding() the input of this request.

public String getContentType() Returns the Internet Media Type of the


request entity data, or null if not known.

public ServletInputStream Returns an input stream for reading


getInputStream() throws binary data in the request body.
IOException

public abstract String Returns the host name of the server that
getServerName() received the request.

public int getServerPort() Returns the port number on which this


request was received.

Example of ServletRequest to display the name of the user


In this example, we are displaying the name of the user in the servlet. For this
purpose, we have used the getParameter method that returns the value for the given
request parameter name.

index.html
<form action="DemoServ" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>

DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

String name=req.getParameter("name");//will return value


pw.println("Welcome "+name);

pw.close();
}}

RequestDispatcher in Servlet
The Request Dispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML file) on
the server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.
As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.
As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.

As you can see in the above figure, response of second servlet is included in the response of
to the client.

How to get the object of RequestDispatcher


The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


public RequestDispatcher getRequestDispatcher(String resource);

Example of using getRequestDispatcher method


RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of the second servlet

rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is
servlet, it will forward the request to the WelcomeServlet, otherwise will show an
error message: sorry username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the database also that we will see
in the development chapter. In this example, we have created following files:

o index.html file: for getting input from the user.


o Login.java file: a servlet class for processing the response. If password is
servet, it will forward the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome
message.
o web.xml file: a deployment descriptor file that contains the information about
the servlet.
As you can see in the above figure, response of second servlet is included in the response of
the first servlet that is being sent to the client.

How to get the object of RequestDispatcher


The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


public RequestDispatcher getRequestDispatcher(String resource);

Example of using getRequestDispatcher method


RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of the second servlet

rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is
servlet, it will forward the request to the WelcomeServlet, otherwise will show an
error message: sorry username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the database also that we will see
in the development chapter. In this example, we have created following files:

o index.html file: for getting input from the user.


o Login.java file: a servlet class for processing the response. If password is
servet, it will forward the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome
message.
o web.xml file: a deployment descriptor file that contains the information about
the servlet.

index.html
<form action="Login" 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("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);

}
}

WelcomeServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class WelcomeServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15. }
16.
17.}

web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/Login</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/WelcomeServlet</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>index.html</welcome-file>
23. </welcome-file-list>
24.</web-app>
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.
Difference between forward() and sendRedirect()
forward() method sendRedirect() method

The forward() method works at server side. The sendRedirect() method

works at client side.

It sends the same request and response objects to another servlet. It always sends a new request.

It can work within the server only. It can be used within and

outside the server.

Example: Example:
request.getRequestDispacher("servlet2").forward(request,response);
response.sendRedirect("servlet2");

method
There are many differences between the forward() method of RequestDispatcher and
sendRedirect() method of HttpServletResponse interface. They are given below:

Syntax of sendRedirect() method


public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method


response.sendRedirect("http://www.javatpoint.com");

Full example of sendRedirect method in servlet


In this example, we are redirecting the request to the google server. Notice that

sendRedirect method works at client side, that is why we can our request to
anywhere. We can send our request within and outside the server.

DemoServlet.java

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

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

response.sendRedirect("http://www.google.com");

pw.close();
}}

Creating custom google search using sendRedirect


In this example, we are using sendRedirect method to send request to google server
with the request data.

index.html

<html>
<head>
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>

MySearcher.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySearcher extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
Session Tracking in Servlets
Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the
new request. So we need to maintain the state of an user to recognize to particular
user.

HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.

A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

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.

Method Description

public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)

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 interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is


used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

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 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
response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
}
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
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

servlet1.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class servlet1 extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29.}

Servlet2.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class servlet2 extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22.}

web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>servlet1</servlet-name>
5. <servlet-class>servlet1</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>servlet1</servlet-name>
10.<url-pattern>/servlet1</url-pattern>
11.</servlet-mapping>
12.
13.<servlet>
14.<servlet-name>servlet2</servlet-name>
15.<servlet-class>servlet2</servlet-class>
16.</servlet>
17.
18.<servlet-mapping>
19.<servlet-name>servlet2</servlet-name>
20.<url-pattern>/servlet2</url-pattern>
21.</servlet-mapping>
22.
23.</web-app>
Servlet Login and Logout Example using
Cookies
A cookie is a kind of information that is stored at client side.

In the previous page, we learned a lot about cookie e.g. how to create cookie, how to
delete cookie, how to get cookie etc.

Here, we are going to create a login and logout example using servlet cookies.

In this example, we are creating 3 links: login, logout and profile. User can't go to
profile page until he/she is logged in. If user is logged out, he need to login again to
visit profile.

In this application, we have created following files.

1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml

<html>
<head>
<title>Servlet Login Example</title>
</head>
<body>
<h1>Welcome to Login App by Cookie</h1>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>
</body>
</html>

File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>

File: login.html
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>

File: LoginServlet.java
package com.javatpoint;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse respo
nse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

String name=request.getParameter("name");
String password=request.getParameter("password");

if(password.equals("admin123")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);

Cookie ck=new Cookie("name",name);


response.addCookie(ck);
}else{
out.print("sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}

out.close();
}

File: LogoutServlet.java
package com.javatpoint;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

Cookie ck=new Cookie("name","");


ck.setMaxAge(0);
response.addCookie(ck);

out.print("you are successfully logged out!");


}
}

File: ProfileServlet.java
package com.javatpoint;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}

File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun
.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javatpoint.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an 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.

Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field


It is widely used in comment form of a website. In such case, we store page id or
page name in the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
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.

index.html
<form action="servlet1">
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 {


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);

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


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>

HttpSession interface
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two
tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of
HttpSession:

1. public HttpSession getSession():Returns the current session associated with


this request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current session and
create is true, returns a new session.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was
created, measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a
request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects
bound to it.
Example of using HttpSession
In this example, we are setting the attribute in the session scope in one servlet and
getting that value from the session scope in another servlet. To set the attribute in
the session scope, we have used the setAttribute() method of HttpSession interface
and to get the attribute, we have used the getAttribute method.

index.html
<form action="servlet1">
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 {

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);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='servlet2'>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();

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>FirstServlet</servlet-class>
</servlet>
1.
<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>

Servlet HttpSession Login and Logout Example


We can bind the objects on HttpSession instance and get the objects by using setAttribute and
getAttribute methods.

In the previous page, we have learnt about what is HttpSession, How to store and get data
from session object etc.

Here, we are going to create a real world login and logout application without using database
code. We are assuming that password is admin123.

In this example, we are creating 3 links: login, logout and profile. User can't go to
profile page until he/she is logged in. If user is logged out, he need to login again to
visit profile.

In this application, we have created following files.

1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml

<html>
<head>
<title>Servlet Login Example</title>
</head>
<body>
<h1>Login App using HttpSession</h1>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>

</body>
</html>

File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>

File: login.html
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>

File: LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse respo
nse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);

String name=request.getParameter("name");
String password=request.getParameter("password");

if(password.equals("admin123")){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}

File: LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse res
ponse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

HttpSession session=request.getSession();
session.invalidate();

out.print("You are successfully logged out!");

out.close();
}
}

File: ProfileServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");

out.print("Hello, "+name+" Welcome to Profile");


}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}

File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun
.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy