Updated Servlet Notes

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

Servlet Tutorial

Servlet technology is used to create web application (resides at server


side and generates dynamic web page).

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.

 Servlet is a technology i.e. used to create web application.


 Servlet is an API that provides many interfaces and classes
including documentations.
 Servlet is an interface that must be implemented for creating any
servlet.
 Servlet is a class that extend the capabilities of the servers and
respond to the incoming request. It can respond to any type of
requests.
 Servlet is a web component that is deployed on the server to create
dynamic web page.
What is 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 components such as HTML. The web components typically
execute in Web Server and respond to HTTP request.

CGI(Commmon 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 number of clients increases, it takes more time for sending


response.
2. For each request, it starts a process and Web server is limited to
start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantage 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 a lot of benefits over the Processes such as they share a common
memory area, lightweight, cost of communication between the threads
are low. The basic benefits 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: Servlets are managed by JVM so we don't need to worry
about memory leak, garbage collection etc.
4. Secure: because it uses java language..

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 of data can be sent because amount of data can be sent
data is sent in header. because data is sent in body.

2) Get request is not secured because Post request is secured because


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

Post request cannot be


3) Get request can be bookmarked.
bookmarked.

4) Get request is idempotent . It


means second request will be ignored Post request is non-
until response of first request is idempotent.
delivered

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

GET and POST

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


client are:

 GET- It requests the data from a specified resource


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

Servlet Vs CGI:

Let’s differentiate Servlet and CGI –

Let’s differentiate Servlet and CGI –


Servlet Vs CGI :
CGI (Common Gateway
Servlet
Interface)

Servlets are portable CGI is not portable.

In Servlets each request is handled IN CGI each request is handled by


by lightweight Java Thread heavy weight OS process

In Servlets, Data sharing is In CGI, data sharing is not


possible available.

Servlets can link directly to the CGI cannot directly link to Web
Web server server.

Session tracking and caching of Session tracking and caching of


previous computations can be previous computations cannot be
performed performed

Automatic parsing and decoding Automatic parsing and decoding of


of HTML form data can be HTML form data cannot be
performed. performed.

Servlets can read and Set HTTP CGI cannot read and Set HTTP
Headers Headers

Servlets can handle cookies CGI cannot handle cookies


CGI (Common Gateway
Servlet
Interface)

Servlets can track sessions CGI cannot track sessions

CGI is more expensive than


Servlets is inexpensive than CGI
Servlets

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 used in java for dynamically generate the web
pages on the server side. Therefore the servlet container is the part of a
web server that interacts with the servlet for handling the dynamic web
pages from the client.

Servlet Container States


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:

 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
 In-process: It is separated from the web server, because a different
program is runs within the address space of the main server as a
plug-in. For example:- Tomcat running inside the JBoss.
 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:
 Life Cycle Management
 Multithreaded support
 Object Pooling
 Security etc.
 Servlet API

1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

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.

Let's see what are the interfaces of javax.servlet package.


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

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

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

Servlet Interface

1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides common behaviour to all the servlets.

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

initializes the servlet. It is the life


public void init(ServletConfig cycle method of servlet and
config) invoked by the web container
only once.
provides response for the
public void service(ServletRequest
incoming request. It is invoked at
request,ServletResponse response)
each request by the web container.

is invoked only once and indicates


public void destroy()
that servlet is being destroyed.

public ServletConfig returns the object of


getServletConfig() ServletConfig.

returns information about servlet


public String getServletInfo()
such as writer,

TYPES OF SERVLETS:

A) Generic Servlet
B) Http Servlet
A) Generic Servlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class

GenericServlet class implements Servlet, ServletConfig and


Serializable interfaces. It provides the implementation of all the
methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-


independent.

Methods of Generic Servlet 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.

Servlet Example by inheriting the GenericServlet class


File: First.java

import java.io.*;

1. import javax.servlet.*;
2.
3. public class First extends GenericServlet
4. {
5. public void service(ServletRequest req,ServletResponse res)
6. throws IOException,ServletException
7. {
8.
9. res.setContentType("text/html");
10.
11. PrintWriter out=res.getWriter();
12. out.print("<html><body>");
13. out.print("<b>hello generic servlet</b>");
14. out.print("</body></html>");
15.
16. }
17. }

B) HttpServlet class
1. HttpServlet class
2. Methods of 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.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res)


dispatches the request to the protected service method by
converting the request and response object into http type.
2. protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the service
method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request. It is invoked
by the web container.
4. protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request. It is invoked
by the web container.
Life Cycle of a Servlet (Servlet Life Cycle)
1. Life Cycle of a 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

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.

6.
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:

1. 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:
1. public void service(ServletRequest request, ServletResponse respo
nse)
2. 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:

1. public void destroy()

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:
Session Tracking Techniques

There are four techniques used in Session tracking:

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

1) 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.
Note: Gmail uses cookie technique for login. If you disable the cookie,
gmail won't work.
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, constructs a cookie with a


String value) specified name and value.

Method Description

Sets the maximum age of the


public void setMaxAge(int expiry)
cookie in seconds.

Returns the name of the cookie.


public String getName() The name cannot be changed
after creation.

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

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.


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.


1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie o
bject
2. 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.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?

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

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing
name and value of cookie
4. }
5.

2) 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.

1. <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.
3) URL Rewriting:

In URL rewriting, we append a token or identifier to the URL of the next


Servlet or the next resource. We can send parameter name/value pairs
using the following format:

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.

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.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information

4) 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.
3.

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.

You might also like