Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

MODULE 2- JAVA SERVLETS

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.

 Portable to any Java application server

 Have access to the entire family of Java and Java EE APIs


 JDBC, Persistence, EJB, JMS, JAX-WS, JTA, JTS, RMI, JNDI, JAXP, ...

 Fundamental part of all Java Web application technologies (JSP, JSF, ...)

 Inherently multi-threaded. Ie, Each request launches a new thread.

 Input from client is automatically parsed into a Request variable.

 A servlet can be thought of as a server-side applet


 Applet: a java program that runs within the web browser
 Servlet: a java program that runs within the web server
 Servlets are loaded and executed by a web server in the same manner that applets are loaded and
executed by a web browser
Why Use Servlets?
 Portability
 Write once, serve everywhere
 Power
 Can take advantage of all Java APIs
 Elegance
 Simplicity due to abstraction
 Efficiency & Endurance
 Highly scalable
 Safety
 Strong type-checking
 Memory management
 Integration
 Servlets tightly coupled with server
 Extensibility & Flexibility
 Servlets designed to be easily extensible, though currently optimized for HTTP uses
 Flexible invocation of servlet (SSI, servlet-chaining, filters, etc.)
Comparison of Servlets with CGI
Common Gateway Interface (CGI)

 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

 Advantages of Servlets over CGI are


1. 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.
2. Servlets are platform-independent because they are written in Java.
3. The Java security manager on the server enforces a set of restrictions to protect the resources on a
server machine. The only way to invoke a servlet from the outside world is through a web server,
which can be protected behind a firewall.
4. 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 and RMI mechanisms that you have seen
already.

II) SERVLET API


 Two packages contain the classes and interfaces that are required to build servlets. These are javax.servlet
and javax.servlet.http . They constitute the Servlet API.

 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 interfaces are


1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
 The use of some of the important interfaces are given below

 There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException Exception Handling

 The use of some of the important classes are given below

 The javax.servlet.http package

 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

 There are many classes in javax.servlet.http package. They are as follows:

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 service() definition is as follows

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.

The destroy() definition is as follows


 These 3 methods are invoked at a specific time as explained below
1. 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.
2. 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.
3. 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.
4. The server invokes the service( ) method of the servlet. This method is called to process
the HTTP request. 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.
5. 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.

IV) CREATING AND RUNNING SERVLETS


 To create and run a servlet application, we need a server to be installed in our system. Here we use Apache
Tomcat server. The steps in creating servlets are
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. Call your servlet from a web browser

 Create a directory structure


 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.

 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 servlet can be created in three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class
3. By inheriting HttpServlet class

 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.

 Compile the Servlet

 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.

 Create a deployment descriptor

 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.

 <servlet> is sub element of <web-app> and represents the servlet.

 <servlet-name> is sub element of <servlet> represents the name of the servlet.

 <servlet-class> is sub element of <servlet> represents the class of the servlet.

 Start the server and deploy the project

 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

 Call your servlet from a web browser

 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

Useful Methods of Cookie class are

 Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other
Interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in


response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from
the browser.

Setting Cookies with Servlet

 Setting cookies with servlet involves three steps −

1. Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value,
both of which are strings.

Cookie cookie = new Cookie("key","value");

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)

FirstServlet.java (to write cookie)


SecondServlet.java (to read cookies)

You might also like