Module - 4 Servlet
Module - 4 Servlet
MODULE -04
SERVLETS & JSP
SERVLETS
Servlet is a technology which is used to create a java based web application. Servlet is an API that
provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet. Servlet is a class that
extends the capabilities of the servers and responds to the incoming requests. It can respond to any
requests.
Servlet is a web component that is deployed on the server to create a dynamic web page.
Servlets offer several advantages in comparison with CGI.
First, 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.
Second, servlets are platform-independent because they are written in Java.
Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software.
Init( ) method
The web container calls the init method only once after creating the Servlet instance.
The init method is used to initialize the Servlet.
Syntax of the init method is
public void init(ServletConfig config) throws ServletException
service ( ) method
The web container calls the service method each time when request for the Servlet is received.
If Servlet is not initialized, it follows the first three steps then calls the service method.
If Servlet is initialized, it calls the service method.
The syntax of the service method of the Servlet interface is given below
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
destroy( ) method
The web container calls the destroy method before removing the Servlet instance from the
service.
It gives the Servlet an opportunity to clean up any resource for example memory, thread etc.
The syntax of the destroy method of the Servlet interface is given below:
public void destroy()
For example, the following command compiles the first servlet example
javac HelloServlet.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat
5.5\common\lib\servlet-api.jar"
Once we have compiled a servlet, we must enable Tomcat to find it. This means putting it into a
directory under Tomcat’s webapps directory and entering its name into a web.xml file.
Procedure followed is
First, copy the servlet’s class file into the following directory:
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-
INF\classes
Next, add the servlet’s name and mapping to the web.xml file in the following directory:
A SIMPLE SERVLET
The basic steps for creating any servlet program is as follow:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper
directory, and add the servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Create and Compile the Servlet Source Code
HelloServlet.java
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Web.xml
<web-app>
<Servlet>
<servlet-name>Example</servlet>
<servlet-class>HelloServlet</servlet>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet>
<url-pattren>/Helloservlet</url-pattren>
</servlet-mapping>
</web-app>
Compile this source code and place the HelloServlet.class file in the proper Tomcat directory.
Add HelloServlet to the web.xml file and then Start Tomcat.
Start a Web Browser and Request the Servlet Start a web browser and enter the URL shown
here: http://localhost:8080/servlets-examples/servlet/HelloServlet.
The most significant of these is Servlet. All servlets must implement this interface or extend a
class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.
The below table summarizes the core classes that are provided in the javax.servlet package:
SERVLET INTERFACE
All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( )
methods that are called by the server during the life cycle of a servlet.
The methods defined by Servlet are shown in Table
Example Program
import java.io.*;
import javax.servlet.*;
public class First implements Servlet
{
ServletConfig config=null;
Web.xml
<web-app>
<servlet>
<servlet-name>ServletInterface</servlet-name>
<servlet-class> First </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletInterface</servlet-name>
<url-pattern>/abc </url-pattern>
</servlet-mapping>
</web-app>
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.
The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.
The methods declared by this interface are
Example
import java.io.*;
import javax.servlet.*;
public class DemoServlet extends GenericServlet
{
public void Service(ServletRequest request, ServletResponse response) throws ServletExce
ption, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration < String > e = config.getInitParameterNames();
String str;
while (e.hasMoreElements())
{
str = e.nextElement();
printWriter.println("<br>Param Name: " + str);
printWriter.println(" value: " + sc.getInitParameter(str));
}
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
SERVLETCONTEXT INTERFACE
The ServletContext interface enables servlets to obtain information about their environment.
Several of its methods are
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Servletrequets.java
import java.io.*;
import javax.servlet.*;
public class DemoServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletExcep
tion, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String str=req.getMimeType(“web.xml”);
out.println(“MIME Type =” +str);
String path=req.getRealPath(“/example/Servletrequest.java”);
out.println(“Real path=” +path);
String info= req.getServerInfo();
out.println(“servlet information=” +info);
out.close();
}
}
SERVLETREQUEST INTERFACE
The ServletRequest interface is used to handle client request to access a servlet i.e it enables a
servlet to obtain information about a client request.
It provides the information of a servlet like content type, content length, parameter names and
values etc.
Several of its methods are
index.html
<form action="test" method="post">
User Name: <input type="text" name="uname"><br>
Password: <input type = "password name = "password"><br>
<input type="submit" value="Log In">
</form>
web.xml
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
ServletDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyServlet1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
{
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setContentLength(10);
out.println("<h2>using ServletResponse</h2>");
out.println("Response ContentType : " + response.getContentType() + "<br/>");
out.println("Response Character Encoding : " + response.getCharacterEncoding() + "<br/>");
}
}
GENERICSERVLET CLASS
The GenericServlet class provides implementations of the basic life cycle methods (init, service,
destroy) for a servlet.
GenericServlet implements the Servlet and ServletConfig interfaces.
In addition, a method to append a string to the server log file is available. The signatures of this
method are:
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
SERVLETINPUTSTREAM CLASS
The ServletInputStream class extends InputStream.
It is implemented by the servlet container and provides an input stream that a servlet developer
can use to read the data from a client request.
It defines the default constructor. In addition, a method is provided to read bytes from the
stream.
It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset.
The method returns the actual number of bytes read or –1 if an end-of-stream condition is
encountered.
SERVLETOUTPUTSTREAM CLASS
The ServletOutputStream class extends OutputStream.
It is implemented by the servlet container and provides an output stream that a servlet developer
can use to write data to a client response.
A default constructor is defined. It also defines the print( ) and println( ) methods, which output
data to the stream.
SERVLET EXCEPTION CLASSES
javax.servlet defines two exceptions.
The first is ServletException, which indicates that a servlet problem has occurred.
PostParameterServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements())
{
String pname = e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
The getParameterNames( ) method returns an enumeration of the parameter names and the parameter
value is obtained via the getParameter( ) method.
JAVAX.SERVLET.HTTP PACKAGE
The javax.servlet.http package contains a number of interfaces and classes that are commonly used
by servlet developers.
The following table summarizes the core interfaces that are provided in this package
HTTPSERVLETREQUEST INTERFACE
The HttpServletRequest interface enables a servlet to obtain information about a client request.
Several of its methods are
Example
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Home extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String at=request. getAuthType();
Pw.print(“Authentication Type” +at);
String m=request. getMethod();
Pw.print(“Method used” +m);
String virtualpath=request. getPathlnfo();
Pw.print(“Path of the servlet is” +virtualpath);
String realpath= getpathTranslated();
Pw.print(“RealPath of the servlet is” +realpath);
String query=getQueryString ();
Pw.print(“Query String of the servlet is” +query);
String sid=getRequestedSessionld();
Pw.print(“Session id =” +sid);
} }
HTTPSERVLETRESPONSE INTERFACE
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
Several constants are defined. These correspond to the different status codes that can be assigned
to an HTTP response.
SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available.
Several methods of this interface are summarized
Example
c.html
<html>
<body>
<form method = “GET” action=”LC”>
<table>
<tr><td> Name <input type=”text” name=”t1” value=”Enter Name”) </td>
</tr>
<tr><td> Password <input type=”text” name=”t1” value=”Enter password”) </td>
</tr>
</table>
</body>
</html>
Web.xml
<web-app>
<servlet>
<servlet-name>Example</servlet>
<servlet-class>LC</servlet>
</servlet>
<servlet>
<servlet-name>Ex</servlet>
<servlet-class>home</servlet>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet>
<url-pattren>/LC</url-pattren>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Ex</servlet>
<url-pattren>/home</url-pattren>
</servlet-mapping>
</web-app>
LC.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class LC extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String name=request.getParameter("t1");
String pass=request.getParameter("t2");
if(name.equals(“admin”) && pass.equals(“123”))
{
String URL= response.encodeRedirectURL(“home.java”);
response.sendRedirect(URL);
}
else
{
String URL= response.encodeRedirectURL(“c.html”);
response.sendRedirect(URL);
sendError(100, “Invalid Username”);
}
}
}
Home.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Home extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Pw.print(“Login Successful”);
}
}
HTTPSESSION INTERFACE
The HttpSession interface enables a servlet to read and write the state information that is
associated with an HTTP session.
Several of its methods are summarized.
All of these methods throw an IllegalStateException if the session has already been invalidated.
HTTPSESSIONBINDINGLISTENER INTERFACE
The HttpSessionBindingListener interface is implemented by objects that need to be notified
when they are bound to or unbound from an HTTP session. The methods that are invoked when
an object is bound or unbound are
void valueBound(HttpSessionBindingEvent e)
void valueUnbound(HttpSessionBindingEvent e)
Here, e is the event object that describes the binding.
COOKIE CLASS
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information. Cookies are valuable for tracking user activities.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the
HttpServletResponse interface.
The data for that cookie is then included in the header of the HTTP response that is sent to the
browser.
The names and values of cookies are stored on the user’s machine.
Some of the information that is saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie
The domain and path of the cookie
There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor.
The methods of the Cookie class are summarized
<center>
<form name="Form1" method="post" action="http://localhost:8080/servlets-
examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie", data);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
HTTPSERVLET CLASS
The HttpServlet class extends GenericServlet. It is commonly used when developing
servlets that receive and process HTTP requests.
The methods of the HttpServlet class are summarized
Index.html
<html>
<body>
<h1> Student Registration Page</h1>
<form action="/StudentServlet" method="get">
Email ID: <input type="email" name="emailId">
Password: <input type="password" name="password">
StudentServlet.java
public class StudentServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
String emailId = req.getParameter("emailId");
String password = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter printWriter = resp.getWriter();
printWriter.print(password);
printWriter.print(emailId);
}
}
HTTPSESSIONEVENT CLASS
HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a
change occurs to the session. It defines this constructor:
HttpSessionEvent(HttpSession session)
Here, session is the source of the event.
HttpSessionEvent defines one method, getSession( ), which is shown here:
HttpSession getSession( )
It returns the session in which the event occurred.
HTTPSESSIONBINDINGEVENT CLASS
The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is
bound to or unbound from a value in an HttpSession object. It is also generated when an attribute
is bound or unbound. Here are its constructors:
HttpSessionBindingEvent(HttpSession session, String name)
HttpSessionBindingEvent(HttpSession session, String name, Object val)
Here, session is the source of the event, and name is the name associated with the object that is
being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.
The getName( ) [ String getName( ) ] method obtains the name that is being bound or unbound.
The getSession( ) [ HttpSession getSession( ) ] method obtains the session to which the listener
is being
The getValue( ) [ Object getValue( ) ]method obtains the value of the attribute that is being
bound or unbound.
<center>
<form method =”POST” action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
SESSION TRACKING
HTTP is a stateless protocol. Each request is independent of the previous one.
In some applications, 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. An HttpSession
object is returned.
This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage
these bindings.
Example
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null)
{
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}