Unit Vi Servlet Part1
Unit Vi Servlet Part1
SERVLETS
Unit Outcomes (UOs): -
Total Marks=14
Introduction to Servlet:
• Servlets are basically the Java programs that run on server. These are the programs that are requested by the XHTML
documents and are displayed in the browser window as a response to the request.
• The servlet class is instantiated when web server begins the execution.
• 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.
• Servlets are most commonly used with HTTP (i.e. Hyper Text Transfer Protocol) hence sometimes
servlets are also called as "HTTP Servlet".
Working of Servlet :
1. When a client make a request for some servlet, he/she actually uses the Web browser in which request is written as a
URL.
2. The web browser then sends this request to Web server. The web server first finds the requested servlet.
3. The obtained servlet gathers the relevant information in order to satisfy the client’s request and builds a web page
accordingly.
4. This web page is then displayed to the client. Thus the request made by the client gets satisfied by the servlets.
Advantages:
• The servlets are very efficient in their performance
• The servlets are platform independent and can be executed on different web servers.
• The servlets working is based on Request- Response. Any HTML form can take the user input and can forward this
input to the servlet.
• Servlets provide a way to generate the dynamic document. For instance : A servlet can display the information of
current user logged in, his logging time, his last access, total number of access he made so far and so on.
• Multiple users can keep a co-ordination for some application among themselves using servlets.
The Life Cycle of Servlet:
In the life cycle of servlet there are three important methods. These methods are
1.Init 2. Service 3. Destroy
The client enters the URL in the web browser and
makes a request the browser then generates the HTTP request and sends it to the Web server.
• Web server maps this request to the corresponding servlet.
1. Init( ) Method : The server basically invokes the init() method of servlet. This method is called only when the
servlet is loaded in the memory for the first time.Using this method initialization parameters
can also be passed to the servlet in order to configure itself.
1. service( ) Method : Server can invoke the service for particular HTTP request using service() method.
The servlets can then read the data provided by the HTTP request with the help of service() method.
1. destroy( ) Method : Finally server unloads the servlet from the memory using the destroy() method.
Creating Simple Servlet
• When we write a servlet program, it is necessary to
- i) Either implement Servlet interface or
- ii) Extend a class that implements Servlet interface.
• While implementing Servlet interface we must include javax.servlet package.
Hence the first line in out servlet program must be
import javax.servlet.*;
• GenericServlet class is a predefined implementation of Servlet interface. Hence we can extend GenericServlet
class in our servlet program. Similarly, the HttpServlet class is a child class of GenericServlet class, hence we can
extend this class as well while writing the servlet program.
Hence following are the two ways by which we can write servlet program
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Test extends GenericServlet
{
//body of servlet
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Test extends HttpServlet
{
//body of servlet
}
• The servlet gets the request from the client for some service. The servlet then processes the request and sends
the response back to the client. In order to handle these issues HttpServletRequest and HttpServletResponse are
used in servlet program.
These requests are handled with the help of some methods that are popularly known as methods of HttpServlet.
These methods are as follows:
The doGet and doPost methods
The protocol of doPost method is same as doGet method. It is as follows - protected void
doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
The GET request is more efficient than the POST request.
The GET request is less secure than the POST request.
Servlet API
There are two packages used to implement the Servlet.
These packages are,
Interface Description
This interface defines all the life cycle methods such as init(),destroy() and service(). All the
servlets must implement this interface. Some of the methods provided by this interface are –
Interface Description
ServletRequest This interface is useful in reading the data from the client request.
ServletResponse This interface is useful in writing the data to the client response.
Servlet Interface
This interface defines all the life cycle methods such as init(),destroy() and service(). All the servlets must implement this
interface. Some of the methods provided by this interface are –
void init(ServletConfig s) → This method is called for initialising the servlet. The initialisation parameter is
obtained from the ServletConfig interface.
void destroy() → This method is called when the servlet has to be unloaded.
void Service(ServletRequest req, ServletResponse res)→ This method is used to implement the service that a servlet
should provide. The clients request is processed and a response is given.
This interface is used to obtain the initialization parameters. Various methods that are used by this interface are
Method Description
String getServletName() This method is used to obtain the name of the servlet.
ServletContext getServletContext() This method returns the context for the servlet.
ServletContext Interface:
This is the interface that enables the servlet to log events and access information about their environment. Various methods
of this interface are:
Method Description
Object getAttribute(String attribute_name) The value of the attribute attribute_name in the current session is
returned.
void setAttribute(String attribute_name, object value) The attribute_name is passed to the object value.
String getServerInfo() This method returns the information about the server.
This interface helps the servlet to formulate the response for the client’s request. Various methods of this interface are –
Method Description
ServletOutputStream getOutputStream() This method returns outputstream which is used to write the data
for responding.
PrintWriter getWriter() This method is used to write the character data to the response.
void setContentLength(int size) This method sets the length of the content equal to the size.
void setContentType(String Type) This methods sets the type of the content.
Classes:
The javax.servlet package contains following classes.
Class Description
ServletInputStream This class provides the input stream for reading the client’s request.
ServletOutputStream This class provides the output stream for writing the client’s response.
ServletException This class is used to raise the exception when an error occurs.
GenericServlet Class
• This class is useful for implementing the life cycle methods such as init(), destroy(), service().
• It implements the servlet and ServletConfig
interfaces.
• It is called "Generic" because it does not assume that the protocol it will process will be HTTP.
Method Description
public void init(ServletConfig config)→ This method is used to initialize the servlet.
public void service (ServletRequest request, ServletResponse response)→ This method provides service for the incoming
request. It is invoked at each time when user requests for a servlet.
public void destroy()→ It is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
public String getServletInfo() → It returns information about servlet such as writer, copyright, version
Interfaces
The following table describes the interfaces that are provided in this package
Interface Description
HttpSession The session data can be read or written using this interface.
HttpServletRequest The servlet can read the information from the HTTP request using this interface.
HttpServletResponse The servlet can write the data to HTTP response using this interface.
HttpSessionBindingListener This interface tells the object about its binding with the particular session.
HttpServletRequest Interface
The HTTPServletRequest is used to obtain the information from client’s HTTP request.
Method Description
String getMethod() It returns the HTTP method for the client request.
String getPathInfo() Returns the path information about the servlet path.
HttpSession getSession() Returns the current session.
String getHeader(String fields) It returns the value of header fields.
Cookie [ ] getCookies() It returns the information in the cookies in the request made.
HttpServletResponse Interface:
This HtttpServletResponse interface is used to formulate an HTTP response to the client. Various methods are –
Method Description
void addCookie(Cookie cookie) This method is used to add cookie in the response.
String encodeURL(String url) This method is used to encode the specified URL.
Boolean containsHeader(String f) This method returns true if the response header contains the field f
void sendError(int code) This method sends error code to the client.
HttpSession Interface:
At every HTTP session, the state information is gathered. The servlet can read or write this information using HTTPSession
interface. This interface is implemented by the server.
Various methods used by this interface are as given below –
Method Description
Object getAttribute(String attribute_name) The value of the attribute attribute_name in the current session is returned.
Class Description
Cookie This class is used to write the cookies
HttpServlet It is used when developing servlets that receive and process HTTP requests
HttpSessionEvent This class is used to handle the session events
HttpSessionBindingEvent When a listener is bound to a value
Cookie Class:
Class Description
void doGet(HttpServletRequest req, HttpServletResponse res) This method performs HTTP get request.
void doPost(HttpServletRequest req, HttpServletResponse res) This method performs HTTP Post request.
void doPut(HttpServletRequest req, HttpServletResponse res) This method performs HTTP Put request.
void service(HttpServletRequest req, HttpServletResponse res) This method is invoked for processing HTTP request and
response.
HttpSessionEvent Class
Object getValue() : This function returns the value of bounded or unbounded attribute.
String getName() : This function returns the name being bound or unbound.
HttpSession getSession() : This function returns the session to which the listener can be bound or unbound.
Handling HTTP Requests and Response:
• Many times we need to pass some information from web browser to Web server. In such case, the HTML document
containing the FORM is written which sends the data to the servlet present on the web server.
• To make the form works with Java servlet, we need to specify the following attributes for the
<form> tag :
(i) method=”method name”: To send the form data as an HTTP POST request to the server.
(ii) action=”URL/address of the servlet”: Specifies relative URL of the servlet which is responsible for handling data
posted from this form.
• The browser uses two methods to pass this information to web server. These methods are GET Method and POST
Method.
(i) GET method : The GET method sends user information along with ? symbol called query string. For instance
http://localhost/hello?user = aaaa&age = 20 In servlet, this information is processed using doGet() method.
(ii) POST method : This is the most reliable method of sending user information to the server HTML form. Servlet
handles this request using
doPost method
Difference between GET and POST:
doGet doPost
1. This Method supports HTTP 1. This Method supports HTTP POST
GET requests. request.
2. Ti can handle only limited 2. It can handle large amount of
amount of data. data.
3. In doGet method user entered 3. In doPost method the user
data is appended to the URL as entered data is not appended to
query string. the URL.
4. Used when security is not 4. Used when security is necessary.
necessary. 5. Syntax:
5. Syntax: public void
public void doPost(HttpServletRequest
doGet(HttpServletRequest request,HttpServletResponse
request,HttpServletResponse response)throws
response)throws ServletException,IOException
ServletException,IOException
How does servlet read form data ?
Servlet makes use of following three methods to read the data entered by the user on the
HTML form
1. getParameter() - You call request.getParameter() method to get the value of a form
parameter.
2. getParameterValues() - Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
3. getParameterNames() - Call this method if you want a complete list of all parameters in
the current request.
Cookies
Definition : Cookies are some little information that can be left on your computer by the other computer when
we access an internet.
• Generally this information is left on your computer by some advertising agencies on the internet. Using
the information stored in the cookies these advertising agencies can keep track of your internet usage, liking
of users.
• For the applications like on-line purchase systems once you enter your personal information such as your
name or your e-mail ID then it can be remembered by these systems with the help of cookies.
• Sometimes cookies are very much dangerous because by using information from your local disk some
malicious data may be passed to you. So it is upto you how to maintain your own privacy and security.
Constructors and Methods
• The cookie class is used to create cookies in servlet.
• The Syntax for constructor for cookies are
o Cookie()
o Cookie(String name, String value)
• Various methods used in Cookie are described in following table
.
1. public string getName() It returns the name of the cookie.
2. public String getValue() It returns the value of the cookie.
3. public string setName() It sets or changes the name of the cookie.
4. public String setValue() It sets or changes the value of the cookie.
5. public void addCookie(Cookie c) The cookie is added in the response object of HttpServletResponse interface.
6. public Cookie[] getCookies() All the cookies can be returned using this method with the help of
HttpServletRequest interface.
Step 1 : Creation of Cookies :
The cookie can be created in Servlet and added to response object using addCookie method
Cookie cookie=new Cookie("user","XYZ");//creating cookie object
response.addCookie(cookie); //adding cookie in the response
• The session tracking technique is a mechanism by which we can keep track of previous sessions between server
and the browser.
• For sending all state information to and fro between browser and server, usually an ID is used. This ID is basically
a session-ID.
• Thus session-ID is passed between the browser and server while processing the information. This method of
keeping track of all the information between server and browser using session-ID is called session tracking.
• In servlets, for creating the sessions getSession() method can be used. This method returns the object which
stores the bindings with the names that use this object. And these bindings can be managed using getAttribute(),
setAttribute(), removeAttribute() methods. Actually in session tracking two things are playing an important role –