Introduction To Servlet
Introduction To Servlet
Servlets are protocol and platform independent server-side software components, written in Java. They
run inside a Java enabled server or application server, such as the WebSphere Application Server.
Servlets are loaded and executed within the Java Virtual Machine (JVM) of the Web server or
application server, in much the same way that applets are loaded and executed within the JVM of the
Web client. Since servlets run inside the servers, however, they do not need a graphical user interface
(GUI). In this sense, servlets are also faceless objects.
What makes servlets a viable choice for web development? We believe that servlets offer a number of
advantages over other approaches, including: portability, power, efficiency, endurance, safety, elegance,
integration, extensibility, and flexibility.
What is Servlet
Servlets are small programs that execute on the server side of a Web connection and dynamically
extend the functionality of a Web server just as applets.
Servlet is an API that provides many interfaces and classes including documentation.
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.
Servlet Architecture
The architecture, is the communication interface, protocol used, requirements of client and server, the
programming with the languages and software involved. Basically, it performs the below-mentioned
tasks.
6. The web server sends the response back to the client and the client browser displays it on the
screen.
Servlets more closely resemble Common Gateway Interface (CGI) scripts or programs than applets in
terms of functionality. As in CGI programs, servlets can respond to user events from an HTML request,
and then dynamically construct an HTML response that is sent back to the client.
The Common Gateway Interface (CGI) is the standard process that uses a set of rules to propagate the
user´s request to the web resources such as web server or web application program and respond to the
user through the web interface. CGI includes several working scripts and programs for web
communication. CGI is the mechanism that is part of the Hypertext Transport Protocol (HTTP). One of
the examples of CGI flow is the Web browsers send the forms data to the backend server, and CGI
connects to the application program on the web-server and the program response to the web browser.
CGI Architecture
Features of CGI
Advantages of CGI
The advanced tasks are currently a lot easier to perform in CGI than in Java.
It is always easier to use the code already written than to write your own.
CGI specifies that the programs can be written in any language, and on any platform, as long as
they conform to the specification.
CGI-based counters and CGI code to perform simple tasks are available in plenty.
Disadvantages of CGI
In Common Gateway Interface each page load incurs overhead by having to load the programs
into memory.
Generally, data cannot be easily cached in memory between page loads.
There is a huge existing code base, much of it in Perl.
CGI uses up a lot of processing time.
Common Gateway Interface(CGI) vs Servlet
A new process is started for each client request. The creation of the process for every such request
requires time and significant server resources which limits the number of requests a server can handle
Servlet
Servlets are server based java application that can link directly to the Web server. Servlets are thread
based applications and work on server level and they share data among each other. All the programs of
Servlets are written in JAVA and they get to run on JAVA Virtual Machine. The following image
describes how a request from clients is served with the help of threads:
CGI Servlet
The CGI programs are written in native OS. Servlet is written in java class & its runs in JVM.
CGI creates a process base for each request. Servlet creates a new thread to process each
request.
The CGI is a language-independent interface The main purpose of servlets is to add up the
that allows a server to start an external process. functionality to
a web server.
A CGI program needs to be loaded and started Servlets stay in the memory while serving the
on each CGI request. requests.
CGI is not able to read the HTTP servers. Servlets are useful to read and set the HTTP
servers.
Servlets are more secure and useful for Data CGI is less secure and is not useful for data sharing.
sharing.
Servlet Life Cycle
Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server.
First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser
then generates an HTTP request for this URL. This request is then sent to the appropriate server.
Second, this HTTP request is received by the Web server. The server maps this request to a
particular servlet. The servlet is dynamically retrieved and loaded into the address space of the
server.
Third, the server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it
may configure itself.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process the
HTTP request. You will see that it is possible for the servlet to read data that has been provided in
the HTTP request. It may also formulate an HTTP response for the client.
The servlet remains in the server’s address space and is available to process any other HTTP
requests received from clients. The service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The algorithms by which this
determination is made are specific to each server. The server calls the destroy() method to
relinquish any resources such as file handles that are allocated for the servlet. Important data may
be saved to a persistent store. The memory allocated for the servlet and its objects can then be
garbage collected.
Servlet API
To create Java Servlets, we need to use Servlet API which contains all the necessary interfaces and
classes. Servlet API has 2 packages namely
javax.servlet
javax.servlet.http
javax.servlet
This package support Generic servlet which is protocol independent. These interfaces and classes
describe and define the contracts between a servlet class and the runtime environment provided by a
servlet container.
Classes Description
ServletInputStream Provides an input stream for reading binary data from a client
request, including an efficient readLine method for reading data
one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletContextEvent This is the event class for notifications about changes to the servlet
context of a web application.
ServletContextAttributeEvent This is the event class for notifications about changes to the
attributes of the servlet context of a web application.
ServletRequestAttributeEvent This is the event class for notifications of changes to the attributes
of the servlet request in an application.
Interface available in javax.servlet package
Interface Description
ServletContext Defines a set of methods that a servlet uses to communicate with its servlet
container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file.
RequestDispatcher Defines an object that receives requests from the client and sends them to any
resource (such as a servlet, HTML file, or JSP file) on the server.
javax.servlet.http
This package describe and define the contracts between a servlet class running under the HTTP
protocol and the runtime environment provided for an instance of such a class by a conforming servlet
container.
Classes Description
HttpSessionBindingEvent 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.
Interface Description
HttpSession Provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.
HttpSessionActivationListener Objects that are bound to a session may listen to container events
notifying them that sessions will be passivated and that session will be
activated.
The directory structure defines that where to put the different types of files so that web container may
get the information and respond to the client.
Create a Servlet
NOTE: The mostly used approach is by extending HttpServlet because it provides http request
HelloWorld.java
..\tomcat\lib\servlet-api.jar
javac HelloWorld.java
If the compilation is successfull then HelloWorld.class file will be generated. Copy *.class file into
document root/WEB-INF/classes folder
Create a deployment descriptor
1. Whenever client makes a request to a servlet that request is received by server and server goes to a
predefined file called web.xml for the details about a servlet.
2. web.xml file always gives the details of the servlets which are available in the server.
3. If the requested servlet is available in web.xml then server will go to the servlet, executes the servlet
and gives response back to client.
4. If the server is not able to find the requested servlet by the client then server generates an error
(resource not found).
web.xml
<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/servletdemo</url-pattern>
</servlet-mapping></web-app>
To start Apache Tomcat server, double click on the startup.bat available at ../tomcat/bin directory.
http://localhost:8080/studyglance/servletdemo
Reading Form Parameters in Servlet
Servlets parse the form(client) data automatically using the following methods depending on the
situation −
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple
values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the current
request
Client pass some information from browser to web server uses GET Method or POST Method.
If a client send the data to the servlet, that data will be available in the object of HttpServletRequest
interface. In case of getParameter() method we have to pass input parameter name and it will give the
value.
request.getParameter("name")
If you are not aware of input parameter name? or if you have more input values its really tedious to use
getParameter() method so we use getParameterNames(). This method returns an Enumeration that
contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop
down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop
and using nextElement() method to get each parameter name.
Enumeration en=request.getParameterNames();while(en.hasMoreElements()){
String param_name = (String) en.nextElement();
String value=request.getParameter(param_name);
.......}
login.html
<html lang="en">
<head>
<title>Login page</title>
</head>
<body>
<h1> Login Form </h1>
<form method="post" action="login">
Username: <input type="text" name="username">
Password: <input type="password" name="pass">
</form>
</body></html>
LoginDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class LoginDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("username"); //will return value
out.println("Welcome "+name);
out.close()
}
}
web.xml
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Reading Initialization Parameters in Servlet
Both ServletContext and ServletConfig are basically the configuration objects which are used by the
servlet container to initialize the various parameter of a web application. But they have some difference
in terms of scope and availability.
ServletConfig ServletContext
ServletConfig object is one per servlet class. ServletContext object is global to the entire web
application.
Object of ServletConfig will be created during the Object of ServletContext will be created at the
initialization process of the servlet. time of web application deployment
We have to give the request explicitly in order to ServletContext object can be available even
create the ServletConfig object for the first time. before giving the first request.
Scope: As long as a servlet is executing, the Scope: As long as a web application is executing,
ServletConfig object will be available, it will be the ServletContext object will be available, and it
destroyed once the servlet execution is completed. will be destroyed once the application is
removed from the server.
ServletConfig object is used while only one ServletContext object is used while application
servlet requires information shared by it. requires information shared by it.
In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.
ServletConfig
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. If the configuration information is modified from the
web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any
specific content is modified from time to time.
Methods of ServletConfig interface
public String getInitParameter(String name): Returns the parameter value for the specified
parameter name.
public Enumeration getInitParameterNames(): Returns an enumeration of all the initialization
parameter names.
public String getServletName(): Returns the name of the servlet
web.xml
<web-app>
<servlet>
<servlet-name>Config</servlet-name>
<servlet-class>ConfigDemo</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>studyglance</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Config</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
ConfigDemo.java
ServletContext
ServletContext object can be used to get configuration information from web.xml file. There is only
one ServletContext object per web application. If any information is shared to many servlet, it is better
to provide it from the web.xml file using the element.
public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
web.xml
<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<servlet>
<servlet-name>Context</servlet-name>
<servlet-class>ContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Context</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
ConfigDemo.java
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the
same user (that is, requests originating from the same browser) across some period of time. 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.
2. URL Rewriting
3. Cookies
4. HttpSession
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden field and get it from another servlet. This approach
is better if we have to submit form in all the pages and we don't want to depend on the browser.
URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.
We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&?
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.
Cookies in Servlet
A cookie is a piece of data from a website that is stored within a web browser(Client side) that the
website can retrieve at a later time. Cookies are used to tell the server that users have returned to a
particular website.
When you send a request to the server, the server sends a reply in which it embeds the cookie which
serves as an identifier to identify the user. So, next time when you visit the same website, the cookie
lets the server know that you are visiting the website again.
Session management. For example, cookies let websites recognize users and recall their individual
login information and preferences, such as sports news versus politics.
Personalization. Customized advertising is the main way cookies are used to personalize your sessions.
You may view certain items or parts of a site, and cookies use this data to help build targeted ads that
you might enjoy.
Tracking. Shopping sites use cookies to track items users previously viewed, allowing the sites to
suggest other goods they might like and keep items in shopping carts while they continue shopping.
The constructor of Cookie class creates the cookie object with corresponding cookie name and value.
cookiedemo.html
<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<form action="servlet1" method="post">
Enter Your Name:<input type="text" name="userName"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
SetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
//creating cookie object
Cookie ck=new Cookie("uname",name);
//adding cookie in the response
response.addCookie(ck);
out.print("Cookie Saved");
//creating submit button
out.print("<br><form action='servlet2' method='post'>");
out.print("<input type='submit' value='View the cookie value'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}}
GetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.println("<h3>Reading the cookies</h3>");
out.println("<br/>");
out.println("Name of the cookie : " + ck[0].getName() + "<br/>");
out.println("Value in cookie : " + ck[0].getValue());
out.close();
}catch(Exception e){
System.out.println(e);
}
}}
web.xml
<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>SetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
HTTPSession in Servlet
A session contains information specific to a particular user across the whole application. When a user
enters into a website (or an online application) for the first time HttpSession is obtained via
request.getSession(), the user is given a unique ID to identify his session.
The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in
deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t
specify the value in tag. This means that when the user doesn’t visit web application time specified, the
session is destroyed by servlet container. The subsequent request will not be served from this session
anymore, the servlet container will create a new session.
setAttribute(String name, Object value): Binds an object to this session, using the name specified.
setMaxInactiveInterval(int interval): Specifies the time, in seconds, between client requests before
the servlet container will invalidate this session.
getAttribute(String name): Returns the object bound with the specified name in this session, or null if
no object is bound under the name.
getAttributeNames(): Returns an Enumeration of String objects containing the names of all the objects
bound to this session.
getId(): Returns a string containing the unique identifier assigned to this session.
invalidate(): Invalidates this session then unbinds any objects bound to it.
removeAttribute(String name): Removes the object bound with the specified name from this session.
sessionemo.html
<html>
<head>
<title>session Demo</title>
</head>
<body>
<form action="servlet1" method="post">
Enter Your Name:<input type="text" name="userName"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
SetSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
// Create a session object.
HttpSession session = request.getSession(true);
session.setAttribute("uname",name);
//creating submit button
out.print("<br><form action='servlet2' method='post'>");
out.print("<input type='submit' value='View the session'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}}
GetSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("uname");
out.print("Hello!.. Welcome "+name);
out.close();
}catch(Exception e){
System.out.println(e);
}
}}
web.xml
<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>SetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping> </web-app>