Unit IV - Servlet
Unit IV - Servlet
Servlet
Introduction
• Servlets are small programs that execute on the server side of a web
connection.
• Just as applets dynamically extend the functionality of a web browser,
servlets dynamically extend the functionality of a web server.
How web browsers and servers provide content to a user
• Consider a request for a static web page.
• A user enters a URL into a browser.
• The browser generates an HTTP request to the appropriate web server.
• The web server maps this request to a specific file.
• That file is returned in an HTTP response to the browser.
• The HTTP header in the response indicates the type of the content. The
Multipurpose Internet Mail Extensions (MIME) are used for this purpose.
• Now consider dynamic content:
• Assume that an online store uses a database to store information about its business.
• This would include items for sale, prices, availability, orders, and so forth.
• It wishes to make this information accessible to customers via web pages.
• The contents of those web pages must be dynamically generated to reflect the latest
information in the database.
Advantages of Servlet
• Performance is significantly better as compared to CGI (Common Gateway
Interface).
(CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response.)
• javax.servlet
• javax.servlet.http
The javax.servlet Package Interfaces
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
information about their
environment.
• The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage
it.
• Servlet container manages the Servlet object.
Source:
https://www.geeksf
orgeeks.org/
1. Loading a Servlet
The Servlet container performs two operations in this stage :
• Loading
• Loads the Servlet class.
• Instantiation
• Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.
2. Initializing a Servlet
• After the Servlet is instantiated successfully, the Servlet container
initializes the Servlet object.
• The container initializes the Servlet object by invoking the
Servlet.init(ServletConfig) method.
• This method is used to initialize the resources, such as JDBC
datasource.
• If the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.
3. Handling request
• After initialization, the Servlet object is ready to serve the client requests.
• To serve the request, the Servlet container performs the following
operations :
• It creates the ServletRequest and ServletResponse objects.
• If this is a HTTP request, then the Web container creates HttpServletRequest and
HttpServletResponse objects which are subtypes of the ServletRequest and
ServletResponse objects respectively.
• After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse)
• The service() method while processing the request may throw the
ServletException or UnavailableException or IOException.
4. Destroying a Servlet
• When a Servlet container decides to destroy the Servlet, it performs
the following operations:
• It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
• After currently running threads have completed their jobs, the Servlet
container calls the destroy() method on the Servlet instance.
Servlet Life Cycle Methods
There are three life cycle
methods of a Servlet :
• init()
• service()
• destroy()
Source: https://www.geeksforgeeks.org/
1. init() method
• init() method is called by the Servlet container to initialize the Servlet
• This method is called only once.
String getParameter(String pname) Returns the value of the parameter named pname.
String getRemoteHost( ) Returns the string equivalent of the client host name.
void setContentType(String Sets the content type for the response to type.
type)
Various Methods Defined by HttpServletRequest
Method Description
String getHeader(String field) Returns the value of the header field named
field.
String getRemoteUser( ) Returns the name of the user who issued this
request.
Various Methods Defined by HttpServletRequest
Method Description
void sendError(int c, String s) Sends the error code c and message s to the
throws IOException client.
void sendRedirect(String url) Redirects the client to url.
throws IOException
void setHeader(String field, Adds field to the header with value equal to
String value) value.
void setStatus(int code) Sets the status code for this response to code.
Handling a data from HTML to Servlet
• Input to servlet is given from the client in the form of name-value
pairs.
• To access this input the following methods are used:
String getParameter(String pname)
Enumeration getParameterNames()
String[] getParameterValues(String name)
• These methods are available in servletReqest interface.
Session Tracking
• HTTP protocol is stateless, means for web server every request is a
new request to process and they can’t identify if it’s coming from the
same client.
• But sometimes in web applications, we should know who the client is
and process the request accordingly.
• For example, a shopping cart application should know who is sending
the request to add an item and in which cart the item has to be added
or who is sending checkout request so that it can charge the amount
to correct client.
There are following ways which provide unique identifier in request and
response:
1. User Authorization
2. URL Rewriting
3. Hidden form fields
4. Cookies
5. Session
1. User Authorization
• This is the very common way where user provides authentication
credentials from the login page.
• Then pass the authentication information between server and client
to maintain the session.
• This is not very effective method because it wont work if the same
user is logged in from different browsers.
2. URL Rewriting
• A session identifier parameter can be appended with every request
and response to keep track of the session.
http://www.example.com/catalog.jsp?userid=123
Method Description
public void addCookie(Cookie c) 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.
Creating Cookie
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
//printing name and value of cookie
out.print("<br>"+c[i].getName()+"
"+c[i].getValue());
}
Cookie have the following disadvantages:
Method Description
public long It returns the time when this session was last
accessed, measured in milliseconds since
getLastAccessedTime() midnight January 1, 1970 GMT.