Unit 6
Unit 6
Servlets
Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request,
produce the response, then send a response back to the webserver.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Properties of Servlets are as follows:
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from the webserver.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets.
After the Servlet is instantiated successfully, the Servlet container initializes the instantiated
Servlet object. The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference as
parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately
after the Servlet.init(ServletConfig) object is instantiated successfully.
public void init(ServletConfig config) throws ServletException
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
There are given 6 steps to create a servlet example. These steps are required for all the servers.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the
WEB-INF folder.
2)Create a Servlet
There are three ways to create the servlet.
1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to handle
http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class.
DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class My extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
pw.println("Hello Servlet"); //writing html in the stream
pw.close();//closing the stream
}}
The javax.servlet and javax.servlet.http are important packages containing the classes and
interfaces that are required for the operation of servlets.
The most commonly used interface from javax.servlet package is Servlet.
Similarly most commonly used class in this package is GenericServlet.
The ServletRequest and ServletResponse are another two commonly used interfaces defined
javax.servlet package.
In the javax.servlet.http package HttpServletRequest and HttpServletResponse are two
commonly used interfaces.
The HttpServletRequest enables the servlet to read data from the HTTP request and
HttpServletResponse enables the servlet to write data to HTTP response.
We have given class name My which should be derived from the class HttpServlet.
(Sometimes we can derive our class from GenericServlet).
Then we have defined service() method to which the HTTP request and response are passed as
parameters.
The commonly used basic exceptions for the servlets are IOException and ServletException.
The response type is specified using the setContentType() method.
PrintWriter is used to create object for output stream.
getWriter() method is used to for obtaining the output stream from response object.
Anything written to this stream , is sent to client as a response.
Hence using object of outout stream pw, we can write the HTML source code in println method as
HTTP response.
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.
web.xml file
<web-app>
<servlet>
<servlet-name>My</servlet-name>
<servlet-class>My</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>My</servlet-name>
<url-pattern>/My</url-pattern>
</servlet-mapping>
</web-app>
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.
1] javax.servlet package
Interfaces in javax.servlet package
A] Servlet Interface
Servlet interface provides common behavior to all the servlets. Servlet interface defines methods
that all servlets must implement.
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.
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
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet
and invoked by the web container only once.
public void service(ServletRequest provides response for the incoming request. It is invoked
request,ServletResponse response) at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
B] ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can be used to get
configuration information from web.xml file.
Methods of ServletConfig interface
1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization
parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.
C] ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the project. This object can be
used to get configuration information from web.xml file.
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml
file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.
D] ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header informations, attributes etc.
There are many methods defined in the ServletRequest interface. Some of them are as follows:
Method Description
public int getContentLength() Returns the size of the request entity data, or -1 if not
known.
public String Returns the character set encoding for the input of this
getCharacterEncoding() request.
public String getContentType() Returns the Internet Media Type of the request entity data,
or null if not known.
public ServletInputStream Returns an input stream for reading binary data in the
getInputStream() request body.
public abstract String Returns the host name of the server that received the
getServerName() request.
public int getServerPort() Returns the port number on which this request was
received.
E] ServletResponse Interface
The servlet container is connected to the web server that receives Http Requests from client on a
certain port.
When client sends a request to web server, the servlet container
creates HttpServletRequest and HttpServletResponse objects and passes them as an argument to
the servlet service() method.
The response object allows you to format and send the response back to the client.
1) String getCharacterEncoding(): It returns the name of the MIME charset used in body of the
response sent to the client.
2) String getContentType(): It returns the response content type. e.g. text, html etc.
3) ServletOutputStream getOutputStream(): Returns a ServletOutputStream suitable for writing
binary data in the response.
4) java.io.PrintWriter getWriter(): Returns the PrintWriter object.
5) void setCharacterEncoding(java.lang.String charset): Set the MIME charset (character
encoding) of the response.
6) void setContentLength(int len): It sets the length of the response body.
7) void setContentType(java.lang.String type): Sets the type of the response data.
2] Classes in javax.servlet package
A] 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.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
A] HttpServletRequest Interface
HttpServletRequest is an interface and extends the ServletRequest interface. By extending the
ServletRequest this interface is able to allow request information for HTTP Servlets. Object of the
HttpServletRequest is created by the Servlet container and, then, it is passed to the service method
(doGet(), doPost(), etc.) of the Servlet.
getAuthType()
Returns the name of the authentication scheme used to protect the servlet.
getHeader(java.lang.String name)
Returns the value of the specified request header as a String.
getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.
getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET,
POST, or PUT.
getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this
request.
getSession()
Returns the current session associated with this request, or if the request does not have a
session, creates one.
B] HttpServletResponse
HttpServletResponse is a predefined interface present in javax.servlet.http package. It can be said
that it is a mirror image of request object. The response object is where the servlet can
write information about the data it will send back. Whereas the majority of the methods in the
request object start with GET, indicating that they get a value, many of the important methods in the
response object start with SET, indicating that they change some property.
addCookie(Cookie cookie)
Adds the specified cookie to the response.
encodeURL(java.lang.String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns
the URL unchanged.
Boolean containsHeader(java.lang.String name)
Returns a boolean indicating whether the named response header has already been set.
sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
GET Method
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? (question mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
Example:
http://localhost:9494/HTTP_PG1/sample?name=Arrow
The GET method is the default method to pass information from browser to web server and it produces
a long string that appears in your browser's Location:box. Never use the GET method if you have
password or other sensitive information to pass to the server. The GET method has size limitation:
only 1024 characters can be used in a request string. Servlet handles this type of requests using
doGet() method.
POST Method
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET method, but instead of sending it as a
text string after a ? (question mark) in the URL it sends it as a separate message. This message comes
to the backend program in the form of the standard input which you can parse and use for your
processing. Servlet handles this type of requests using doPost() method.
sample.java file
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class sample extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close();
}
}
Example 2:
Index.html
<html>
<body>
<h1>The select element</h1>
<p>The select element is used to create a drop-down list.</p>
<form name= "form1" method=Get action="http://localhost:9494/HTTP_PG2/sample">
<label>Choose a car:</label>
<select name="cars" id="cars">
<option value="Maruti">Maruti</option>
<option value="BMW">BMW</option>
<option value="Lexus">Lexus</option>
<option value="Audi">Audi</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
sample.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class sample extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String name=req.getParameter("cars");//will return value
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("Selected car is "+name);
pw.close();
}}
Example 3:- Display the Greatest of the two numbers entered by User
Index.html
<html>
<body>
<h1>The select element</h1>
<form name= "form1" method=Get action="http://localhost:9494/HTTP_PG3/sample">
<label>Enter First Number</label>
<input type="text" name="Number1" size="5"><br><br>
<label>Enter Second Number</label>
<input type="text" name="Number2" size="5">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
sample.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class sample extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
int a=Integer.parseInt(req.getParameter("Number1"));
int b=Integer.parseInt(req.getParameter("Number2"));
if (a>b)
pw.println("Greatest Number is "+a);
else
pw.println("Greatest Number is "+b);
pw.close();
}}
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.
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.
Types of Cookie
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.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.
Cookie(String name, String value) constructs a cookie with a specified name and value.
There are given some commonly used methods of the 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.
sample1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sample1 extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
Cookie ck=new Cookie("uname",n); //creating cookie object
response.addCookie(ck); //adding cookie in the response
out.println("Your Cookie Added Successfully!!!");
out.println("Welcome "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
HttpSession interface
Here 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.
index.html
<html>
<body>
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='SecondServlet'>visit</a>");
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>