Module 2-Java Servlets: I) Introduction
Module 2-Java Servlets: I) Introduction
I) INTRODUCTION
Servlets are small java programs that execute on the server side of a web connection. Servlets dynamically
extend the functionality of a web server
Although servlets can respond to any types of requests, they most commonly implement applications hosted
on Web servers. Such Web servlets are the Java counterpart to other dynamic Web content technologies
such as PHP and ASP.NET
Provide a general framework for services built on the request-response paradigm. Java Servlets act as a
middle layer between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server. 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.
Fundamental part of all Java Web application technologies (JSP, JSF, ...)
a standard way for a Web server to pass a Web user's request to an application program and to receive data
back to forward to the user
Use standard input and output for data exchange
Programming language independent
Weakness are
CGI program may not be easily portable to other platform. CGI scripts are typically written in Perl or
C, and are very much tied to a particular server platform
Substantial overhead is incurred in starting the CGI process
Contains many interfaces and classes that are used by the servlet or web container. These are not
specific to any protocol.
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException Exception Handling
Contains interfaces and classes that are responsible for http requests only.
There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
III) ARCHITECTURE AND LIFE CYCLE OF JAVA SERVLET
ARCHITECTURE
1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
2. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
3. Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
4. Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
5. Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
LIFE CYCLE
Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). All
the life cycle methods are invoked by the web container according to the state change of servlet.
.
init()
it is life cycle’s method of servlet and this is invoked when server initialize the servlet instance. This
method is used to provide initial parameters to servlet and it takes ServletConfig object as argument.
It is called only once and after just servlet instance creation.
The init() definition is as follows
service()
this method is invoked by server for each request come from client. Here developer writes logics to
process client’s request.
The doGet() and doPost() are most frequently used methods with in each service
request.
A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method
destroy()
this method is invoked by server when servlet instance about to destroy or going to unavailable.
Developer use this method to process some finalization task like database connection closing, data
flushing etc.
All HTML, static files(images, css etc) are kept directly under Web application folder. While all the
Servlet classes are kept inside classes folder.The web.xml (deployement descriptor) file is kept under
WEB-INF folder.
Create a Servlet
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost() etc
A servlet program TestingServlet is given below.
Write above code in a notepad file and save it as TestingServlet.java anywhere on your PC. Compile
it(explained in next step) from there and paste the class file into WEB-INF/classes/ directory.
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat
server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet
1. Set classpath
2. Download and paste the jar file in JRE/lib/ext folder
3. Compile the servlet file as javac TestingServlet.java
4. Paste the class file into WEB-INF/classes/ directory.
The deployment descriptor is an xml file, from which Web Container gets the information about the
servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml
parsers such as SAX, DOM
A simple web.xml file for our web application is given below
<web-app> represents the whole application.
Double click on the startup.bat file to start your Apache Tomcat Server. Or, execute the following
command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat
open a browser window and type the URL http://localhost:8080/directory (folder name of your
application) name/servler name and press enter.
Eg:- http://localhost:8080/TestingServlet
V) COOKIE CLASS
Cookies are text files stored on the client computer and they are kept for various information tracking
purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users –
1. Server script sends a set of cookies to the browser. For example name, age, or identification number
etc.
2. Browser stores this information on local machine for future use.
3. When next time browser sends any request to web server then it sends those cookies information
to the server and server uses that information to identify the user.
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.
Constructor of Cookie class are
For adding cookie or getting the value from the cookie, we need some methods provided by other
Interfaces. They are:
1. Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value,
both of which are strings.
Neither the name nor the value should contain white space or any of the following characters
[]()=,"/?@:;
2. Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should
be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
3. Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies
in the HTTP response header as follows −
response.addCookie(cookie);
The example code shows how to write and read cookies
Index.html (client request)