Servlets
Servlets
Servlets
Suhasini Shukla
Servlets
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.4 Handling Http Requests and Responses, Handling HTTP GET Requests, Handling HTTP POST
Requests
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
• 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.
• 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
• On receiving a request, the web server interprets it using some protocol and always returns
some kind of result (response) to the web browser.
Web browser
• The browser acts as a universal user interface and allows viewing and accessing various types of
internet resources available on the world wide web.
• (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.
• The HTTP header in the response indicates the type of the content.
• 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
• 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.
• 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 servlet is dynamically retrieved and loaded in to the address space of the server.
init() method
• 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:
• During initialization, the servlet has access to two key parameters, ServletConfig and
ServletContext.
• 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
• Syntax
• 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.
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:
• 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.
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
Can be used with any protocol such Only used with HTTP protocol.
as HTTP, SMTP, FTP, and, CGI
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
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.
• 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.
• If no expiration date is assigned to a cookie, then the cookie is deleted when current browser
session ends.
• 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.
Types of Cookie
• 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(String name, String value): Constructs a cookie with a specified name and value.
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 Cookie[] getCookies(): method of HttpServletRequest interface is used to return all the
cookies from the browser.
Session Tracking
• 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.
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 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.