Servlets

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

Advanced Java Programming TYCO Mrs.

Suhasini Shukla

Servlets

Topics and sub-topics

 6.1 The life cycle of a servlet

 6.2 Creating a simple servlet: The servlet API, javax.servlet package, Servlet Interface,
ServletConfif Interface, ServletContext Interface, ServletRequest Interface, ServletResponse
Interface, Generic Servlet class.

 6.3 The javax.servlet.http package, HttpServletRequest Interface, HttpServletResponse


Interface,, HttpSession Interface, Cookie class, HttpServlet class, HttpSessionEvent class,
HttpSessionBindingEvent class.

 6.4 Handling Http Requests and Responses, Handling HTTP GET Requests, Handling HTTP POST
Requests

 6.5 Cookies and Session tracking

Unit Outcomes

 6a. Explain the function of the given method of servlet life cycle.

 6b. Use relevant generic servlet to develop given web based application.

 6c. Use relevant HTTP servlet to develop specified web based application

 6d. Develop servlet for cookies and session tracking to implement the given problem

Servlet

• Servlet is a technology used to create web applications.

• It is a web component that is deployed on the server to create a dynamic web page.

• They have the capability to change the site contents according to the time or are able to
generate the contents according to the request received by the client.

• They are small Java programs that execute on the server side of the web application.

• As applets extend the functionality of web browser, servlets extend the functionality of web
server.

• This is done dynamically.

The process of accessing information

• There are two types of computers that must be dealt with.

• Computers which offer information to be read called server.

• Computers that read information offered called client on which web browser is used.

• A web server or http server is a program running on the server(i.e. on physical computer)
Advanced Java Programming TYCO Mrs. Suhasini Shukla

• It waits for incoming requests.

• On receiving a request, the web server interprets it using some protocol and always returns
some kind of result (response) to the web browser.

Popular web servers

• Apache Tomcat web server

• Microsoft IIS(Internet Information Server)

Web browser

• It is a client to the web server.

• The browser acts as a universal user interface and allows viewing and accessing various types of
internet resources available on the world wide web.

Web browser responsibilities

• Issuing requests to the web server

• Handling any results generated by the requests

• Presenting (Rendering) web content to the user.

URL (Uniform Resource Locator)

• A protocol (for e.g. HTTP)

• A server (Domain) Name from which the information is requested.

• The port number on which the server is listening (optional)

• The filename which stores the information (optional)

• (http://www.msbte.org.in:8080/index.html)

How Web browser and web servers cooperate to provide contents to the user

• A request for a web page comes from the user in the form of a URL.

• The browser generates HTTP request to the appropriate web server, which maps the request to
a specific file.

• That file is returned in and HTTP response to the browser.

• The HTTP header in the response indicates the type of the content.

• MIME( Multipurpose Internet Mail Extensions)

Web server’s responsibilities

• Must be able to invoke the program at its side.


Advanced Java Programming TYCO Mrs. Suhasini Shukla

• When a user makes a request from a web browser, the server must be able to locate the
information, determine its type and execute the program.

• There must be a way in which the web server passes the form data received from the browser
to the server side program. When the web server invokes the server side program, it needs a
way to pass HTTP request to the program

• There has to be a standard entry point as soon as the program is invoked.

• On completion of processing the input data, the program has to bundle up the results and send
it back to the server, which sends it to the browser that requested it.

Life cycle of Servlet

• Three methods that are important in the life cycle of the servlet are init(), service() and
destroy().

• They are implemented by every servlet and are invoked at specific times by the server.

• When a user enters a URL in the browser, the browser generates an HTTP request for this URL.

• The request is sent to the appropriate server.

• The HTTP request is received by the server.

• The server maps the request to a particular servlet.

• The servlet is dynamically retrieved and loaded in to the address space of the server.

init() method

• The server invokes the init() method of the servlet.


Advanced Java Programming TYCO Mrs. Suhasini Shukla

• The init() method is invoked only when the servlet is loaded for the first time in the memory.

• It is possible to pass initialization parameters to the servlet so that the servlet can configure
itself.

• Syntax:

• public void init (ServletConfig config) throws ServletException

• During initialization, the servlet has access to two key parameters, ServletConfig and
ServletContext.

• This is because init() receives the object of ServletConfig as parameter.

• When the servlet is setup for the first time, the configuration data such as information about
parameters and references to the ServletContext is stored in the ServletConfig object.

service() method

• The server invokes the service() method to process an HTTP request

• Syntax

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException

• Each client’s request to the service method is run in a separate servlet thread.

• This method uses ServletRequest object to collect the data requested by the client.

• This method uses ServletResponse object to generate the output content.

destroy() method

• The servlet remains in the address space of the server and is available to process any other HTTP
request received from the client.

• The server may decide to unload the servlet from its memory. This is done by calling the
destroy() method.

• Syntax:

public void destroy()

• The servlet is eligible for garbage collection. All resources allocated to the servlet in the init()
method must be released in the destroy() method.

• This method performs various tasks such as closing the connection with the database,
releasing the memory allocated to the servlet, releasing recourses and other clean up
activities.

• When this method is called, the garbage collector comes into action.

• This method is called only once in the life cycle of the servlet.
Advanced Java Programming TYCO Mrs. Suhasini Shukla

Servlet API

• Following are the two packages that contain the classes and interfaces required to build
servlets.

1. javax.servlet: Used for generic servlets

2. Javax.servlet.http: Used for http and https protocols

Javax.servlet

Interfaces

• Servlet

• ServletRequest

• ServletResponse

• ServletConfig

• ServletContext

Classes

• GenericServlet

• ServletInputStream

• ServletOutputStream

Javax.servlet.http

Interfaces

• HttpServletRequest

• HttpServletResponse

• HttpSession

Classes

• HttpServlet

• Cookie

• HttpSessionBindingEvent
Advanced Java Programming TYCO Mrs. Suhasini Shukla

Difference between Generic Servlet and HTTP Servlet

Generic Servlet HTTP Servlet

GenericServlet is protocol independent HttpServlet is protocol dependent

Can be used with any protocol such Only used with HTTP protocol.
as HTTP, SMTP, FTP, and, CGI

Difference between doGet() and doPost()

doGet() doPost()

In doGet() the parameters are appended to the URL In doPost(), parameters are sent in separate line in the
and sent along with header information body

Maximum size of data that can be sent using doget() There is no maximum size for data
is 240 bytes

Parameters are not encrypted Parameters are encrypted

doGet() method generally is used to query or to get doPost() is generally used to update or post some
some information from the server information to the server

doGet() is faster if we set the response content doPost() is slower compared to doGet() since doPost()
length since the same connection is used. Thus does not write the content length
increasing the performance.

The Cookie class

• This class encapsulates a cookie.

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

• Cookies are text files stored on the client computer and they are kept for various information
tracking purpose.

• Cookie is stored on the client machine and contains state information.

• Cookies are used for tracking user activities.

• Following information is saved for each cookie

1. The name of the cookie

2. The value of the cookie


Advanced Java Programming TYCO Mrs. Suhasini Shukla

3. The expiration date

4. The domain and path of the cookie.

The expiration date

• It determines when the cookie will be deleted from the machine.

• If no expiration date is assigned to a cookie, then the cookie is deleted when current browser
session ends.

• Otherwise the cookie is saved in a file on the user’s machine.

Domain and Path of the Cookie

• It determines when the cookie is included in the header of an HTTP request.

• If the user enters a URL whose domain and path match theses values, the cookie is then
supplied to the web server, otherwise it is not supplied.

How does a cookie work?

Types of Cookie

There are 2 types of cookies in servlets.

• Non-persistent cookie

• Persistent cookie
Advanced Java Programming TYCO Mrs. Suhasini Shukla

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 sessions. It is not removed each time when user closes the
browser. It is removed only if user logs out or signs out.

Constructor of Cookie

Cookie(): Constructs a cookie.

Cookie(String name, String value): Constructs a cookie with a specified name and value.

Methods of Cookie class

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in 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 name) Changes the name of the cookie.

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

Methods needed for using cookie class

• public void addCooie(Cookie ck): method of HttpServletResponse interface is used to


add cookie in response object.

• public Cookie[] getCookies(): method of HttpServletRequest interface is used to return all the
cookies from the browser.

Session Tracking

• HTTP is a stateless protocol.

• Each request is independent of previous one.

• Sessions are used when it is necessary to save state information so that information can be
collected from several interactions between a browser and a server.

• A session can be created via the getSession() method of HttpServletRequest.


Advanced Java Programming TYCO Mrs. Suhasini Shukla

Methods of HttpSession class

Method Description

public void setAttribute(String name, Binds the object with a name and stores the name/value
Object value) pair as an attribute of the HttpSession object. If an
attribute already exists, then this method replaces the
existing attributes.

public Object getAttribute (String Returns the String object specified in the parameter, from
name) the session object. If no object is found for the specified
attribute, then the getAttribute() method returns null.

public Enumeration Returns an Enumeration that contains the name of all the
getAttributeNames() objects that are bound as attributes to the session object.

public void removeAttribute (String Removes the given attribute from session.
name)

HttpSessionEvent class, HttpSessionBindingEvent class.

• HttpSessionEvent class gives notifications for changes to sessions within a web application.

• HttpSessionBindingEvent class constructs an event that notifies an object that it has been
bound to or unbound from a session. To receive the event, the object must implement
HttpSessionBindingListener.

• Events of this type are either sent to an object that implements HttpSessionBindingListener
when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been
configured in the deployment descriptor when any attribute is bound, unbound or replaced in
a session.

• The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a
call to HttpSession.removeAttribute.

You might also like