You are on page 1of 211

Enterprise Java

Lecture 5
Java Servlets
Introduction
• A web server uses HTTP protocol to transfer
data
• The transformation is in HTTP protocol which
specifies the format of request and response
message.
Introduction
• At the beginning, web servers delivered static
contents that are indifferent to users'
requests.
• Java servlets are server-side programs
(running inside a web server) that handle
clients' requests and return a customized or
dynamic response for each request.
Introduction
• The dynamic response could be based on
user's input (e.g., search, online shopping,
online transaction) with data retrieved from
databases or other applications, or time-
sensitive data (such as news and stock prices).
• Java servlets typically run on the HTTP
protocol.
Introduction
• HTTP is an asymmetrical request-response
protocol.
• A HTTP Servlet runs under the HTTP protocol.
• It is important to understand the HTTP
protocol in order to understand server-side
programs (servlet, JSP, ASP, PHP, etc) running
over the HTTP.
Introduction
• In brief, HTTP is a request-response protocol.
• The client sends a request message to the
server.
• The server, in turn, returns a response
message.
• The messages consists of two parts: header
(information about the message) and body
(contents).
Introduction
• Header provides information about the
messages.
• The data in header is organized in name-value
pairs.
• The client sends a request message to the
server, and the server returns a response
message as illustrated.
The request-response relationship
between server and client
Server-Side Technologies
• There are many (competing) server-side
technologies available: Java-based (servlet,
JSP, JSF, Struts, Spring, Hibernate), ASP, PHP,
CGI Script, and many others.
• Java servlet is the foundation of the Java
server-side technology, JSP (JavaServer Pages),
JSF (JavaServer Faces), Struts, Spring,
Hibernate, and others, are extensions of the
servlet technology.
Servlet Technology
• Servlet technology is used to create web
application (resides at server side and
generates dynamic web page).
• Servet technology is robust and scalable as it
uses the java language.
• There are many interfaces and classes in the
servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse
etc.
Servlet Technology
• Before Servlet, CGI (Common Gateway
Interface) scripting language was used as a
server-side programming language.
• But there were many disadvantages of this
technology.
Common Gateway Interface (CGI)
• CGI technology enables the web server to call an
external program and pass HTTP request
information to the external program to process
the request.
• For each request, it starts a new process.
• Disadvantages of CGI
– If number of clients increases, it takes more time for
sending response.
– For each request, it starts a process and Web server is
limited to start processes.
– It uses platform dependent language e.g. C, C++, perl.
Common Gateway Interface (CGI)

Server
CGI CGI
Request httpd shell program

Request CGI
shell
Request
CGI
shell
Advantage of Servlet
• There are many advantages of Servlet over
CGI.
• The web container creates threads for
handling the multiple requests to the servlet.
• Threads have a lot of benefits over the
processes such as they share a common
memory area, lightweight, cost of
communication between the threads are low.
Advantage of Servlet

Web Server
Request Web Container
Thread
Request
Thread Servlet
Request
Thread
Advantage of Servlet
• The basic benefits of servlet are as follows:
– better performance: because it creates a thread
for each request not process.
– Portability: because it uses java language.
– Robust: Servlets are managed by JVM so no need
to worry about memory leak, garbage collection
etc.
– Secure: because it uses java language.
Apache Tomcat Server
• Servlets are server-side programs run inside a
Java-capable HTTP server.
• Apache Tomcat Server is the official Reference
Implementation (RI) for Java servlet and JSP,
provided free by open-source foundation
Apache
• Install Tomcat to try out Java servlets.
Apache Tomcat Server
• Tomcat is a fully functional implementation of
the JSP and servlet standards
• It includes a web server, so it can be used as a
standalone test container for JSPs and servlets
• Tomcat also can be specified as the handler
for JSP and servlet requests received by
popular web servers such as the Apache
Software Foundation’s Apache HTTP server or
Microsoft’s Internet Information Services (IIS)
Installing Tomcat Server
• Download the latest version of Tomcat from
http://tomcat.apache.org/download-70.cgi
Installing Tomcat Server
• Download binary distributions for 32 bit/64
bit (depending on the PC architecture)
Installing Tomcat Server
• Extract the contents of the archive file to a
directory in the hard disk
• For Tomcat to work define environmental
variables (Control panel  Advanced system
setting  Environmental variables  System
variables)
– JAVA_HOME – should point to the directory
containing the Java installation (C:\Program
Files\Java\jdk1.7.0)
– CATALINA_HOME – point to the directory containing
Tomcat (G:\Tomcat\apache-tomcat-8.0.0-RC10-
windows-x64\apache-tomcat-8.0.0-RC10)
Starting Tomcat Server
• After setting up the environmental variables,
start the Tomcat server
– Open command prompt and change to the bin
directory
– Go to bin directory inside the directory containing
the Tomcat files
– The files startup.bat, shutdown.bat, startup.sh,
shutdown.sh are available for starting and
stopping the Tomcat server on Windows and
Unix/Linux/Mac OS X
Starting Tomcat Server
• To start the server type
– startup
• To verify that Tomcat is executing, enter the
URL http://localhost:8080/
Starting Tomcat Server
Starting Tomcat Server
Shutdown Tomcat Server
• To shutdown the Tomcat server issue the
command
– shutdown
Deploying a web application
• JSP, servlets and their supporting files are
deployed as part of web applications
• These are deployed in the webapps
subdirectory contained in the Tomcat
directory
• The web application directory structure
contains a context root – top level directory
for an entire web application and several
subdirectories
Configuring the context root
• Configuring the context root for a web
application in Tomcat requires creating a sub-
directory in the webapps directory
• When Tomcat begins execution, it creates a
context root for each subdirectory of
webapps, using each subdirectory’s name as
the context root name
• For example, we will create the directory jhtp5
in Tomcat’s webapps directory
Web application standard directories
Directory Description
context root This is the root directory of the web application. All JSPs, HTML
documents, servlets and supporting files such as images and class
files reside in this directory or its subdirectories. The name of this
directory is specified by the web application creator. To provide
structure in a web application, subdirectories can be placed in the
context root. Eg: If the application uses many images they can be
placed in a subdirectory in this directory. Eg: jhtp5 is the context
directory in our examples
WEB-INF This directory contains the web application deployment descriptor
(web.xml)
WEB-INF/classes This directory contains the servlet class files and other supporting
class files used in a web application. If classes are part of a package,
the complete package structure is placed here
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can
contain servlet class files and other supporting class files used in a
web application
The webapps directory
• Create the context root named jhtp5 in the
webapps directory of Tomcat server
• Create the following sub folders inside the
context root jhtp5 directory
– servlets folder
• Contains all .html files (in our examples)
– WEB-INF folder
• Contains the deployment descriptor ‘web.xml’
• Contains the folder called ‘classes’
– All servlets are placed here
Java Servlet Versions
• J2EE 1.2 (December 12, 1999) (Java Servlet 2.2, JSP 1.1,
EJB 1.1, JDBC 2.0)
• J2EE 1.3 (September 24, 2001) (Java Servlet 2.3, JSP
1.2, EJB 2.0, JDBC 2.1)
• J2EE 1.4 (November 11, 2003) (Java Servlet 2.4, JSP 2.0,
EJB 2.1, JDBC 3.0)
• Java EE 5 (May 11, 2006) (Java Servlet 2.5, JSP 2.1, JSTL
1.2, JSF 1.2, EJB 3.0, JDBC 3.0)
• Java EE 6 (December 10, 2009) (Java Servlet 3.0, JSP
2.2/EL 2.2, JSTL 1.2, JSF 2.0, EJB 3.1, JDBC 4.0)
• Java EE 7 (June 12, 2013) (Java Servlet 3.1, JSP 2.3/EL
3.0, JSTL 1.2, JSF 2.2, EJB 3.2, JDBC 4.0)
Java Servlets
• Java Servlet is the foundation technology for
Java server-side programming.
• You need to understand Servlet thoroughly
before you could proceed to other Java server-
side technologies such as JavaServer Pages
(JSP) and JavaServer Faces (JSF).
Java Servlets
• Servlet can be described in many ways, depending on
the context.
– Servlet is a technology i.e. used to create web application.
– Servlet is an API that provides many interfaces and classes
including documentations.
– Servlet is an interface that must be implemented for
creating any servlet.
– Servlet is a class that extend the capabilities of the servers
and respond to the incoming request. It can respond to
any type of requests.
– Servlet is a web component that is deployed on the server
to create dynamic web page.
Java Servlets

1) Request
Client Server

2) Response is
3) Response is
generated at
sent to the client
runtime

Content
Web application
• A web application is an application accessible
from the web.
• A web application is composed of web
components like Servlet, JSP, Filter etc. and
other components such as HTML.
• The web components typically execute in Web
Server and respond to HTTP request.
Servlet Terminology
• The basic terminology used in servlet are given
below:
– HTTP
– HTTP Request Types
– Difference between Get and Post method
– Container
– Server and Difference between web server and
application server
– Content Type
– Introduction of XML
– Deployment
HTTP (Hyper Text Transfer Protocol)
• Http is the protocol that allows web servers
and browsers to exchange data over the web.
• It is a request response protocol.
• Http uses reliable TCP connections by default
on TCP port 80.
• It is stateless means each request is
considered as the new request.
• In other words, server doesn't recognize the
user by default.
Http Request Methods
• Every request has a header that tells the
status of the client.
• There are many request methods.
• Get and Post requests are mostly used.
Http Request Methods
• The http request methods are:
– GET
– POST
– HEAD
– PUT
– DELETE
– OPTIONS
– TRACE
Http Request Methods
HTTP Request Description
GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
What is the difference between Get
and Post?
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data can
data can be sent because data is sent in header. be sent because data is sent in body.

2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked

4) Get request is idempotent. It means second Post request is non-idempotent


request will be ignored until response of first
request is delivered.

5) Get request is more efficient and used more Post request is less efficient and used less than get.
than Post
Anatomy of Get Request
• The data is sent in request header in case of
get request.
• It is the default request type.
Anatomy of Post Request
• In case of post request original data is sent in
message body.
Container
• It provides runtime environment for JavaEE
(j2ee) applications.
• It performs many operations that are given
below:
– Life Cycle Management
– Multithreaded support
– Object Pooling
– Security etc.
Servlet Container
• The basic idea of Servlet container is using
Java to dynamically generate the web page on
the server side based on user input.
• Servlet container is essentially a part of a web
server that interacts with the servlets.
• Servlet container is the container for Servlets.
Servlet Container
• Like any Java program, the servlet runs within
a JVM.
• To handle the complexity of HTTP requests,
the servlet container comes in.
• The servlet container is responsible for
servlets’ creation, execution and destruction.
Server
• It is a running program or software that
provides services.
• There are two types of servers:
– Web Server
– Application Server
Web Server
• Web server contains only web or servlet
container.
• It can be used for servlet, jsp, struts, jsf etc.
• It can't be used for EJB.
• Example of Web Servers are: Apache
Tomcat and Resin.
Application Server
• Application server contains Web and EJB
containers.
• It can be used for servlet, jsp, struts, jsf, ejb etc.
• Example of Application Servers are:
– JBoss Open-source server from JBoss community.
– Glassfish provided by Sun Microsystem. Now acquired
by Oracle.
– Weblogic provided by Oracle. It more secured.
– Websphere provided by IBM.
Content Type
• Content Type is also known as MIME
(Multipurpose Internet Mail Extension) Type.
• It is a HTTP header that provides the
description about what are you sending to the
browser.
Content Type
• There are many content types:
– text/html
– text/plain
– application/msword
– application/vnd.ms-excel
– application/jar
– application/pdf
– application/octet-stream
– application/x-zip
– images/jpeg
– video/quicktime etc.
Servlet API
• The javax.servlet and javax.servlet.http packages
represent interfaces and classes for 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 javax.servlet.http package contains interfaces
and classes that are responsible for http requests
only.
Interfaces in javax.servlet package
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Classes in javax.servlet package
• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• ServletException
• UnavailableException
Interfaces in javax.servlet.http
package
• HttpServletRequest
• HttpServletResponse
• HttpSession
• HttpSessionListener
• HttpSessionAttributeListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
• HttpServlet
• Cookie
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpSessionEvent
• HttpSessionBindingEvent
• HttpUtils (deprecated now)
Servlet Interface
• Servlet interface provides common behaviour
to all the servlets.
• 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
Interface Servlet
• All servlets implement the Servlet interface.
• The methods of interface Servlet is implemented
by the servlet container
• Package containing Servlet interface is
javax.servlet
• It declares three essential methods for the
lifecycle of a servlet – init(), service(), and
destroy().
• They are implemented by every servlet(defined in
SDK or self-defined) and are invoked at specific
times by the server.
Methods of interface Servlet
Method Description
void init(ServletConfig config) Servlet container calls this method once during a
servlet’s execution cycle to initialize the servlet. The
ServletConfig argument is supplied by the servlet
container that executes the servlet. It is the life cycle
method of servlet and invoked by the web container
only once
ServletConfig getServletConfig() This method returns a reference to an object that
implements interface ServletConfig. This object
provides access to the servlet’s configuration
information such as servlet initialization parameters
and the servlet’s ServletContext, which provides the
servlet with access to its environment (i.e. the servlet
container in which the servlet executes)
Methods of interface Servlet
Method Description
String getServletInfo() This method is defined by a servlet programmer to
return a string containing servlet information such as
the servlet’s author and version. returns information
about servlet such as writer, copyright, version etc.
void service(ServletRequest The servlet container calls this method to respond to a
request, ServletResponse client request to the servlet. It is invoked at each request
response) by the web container.
void destroy() This “cleanup” method is called when a servlet is
terminated by its servlet container. Resources used by
the servlet, such as an open file or an open database
connection, should be deallocated here. It is invoked
only once and indicates that servlet is being destroyed.
Invoking Methods of a Servlet
1) The init() method is invoked during initialization stage of
the servlet life cycle. It is passed an object implementing
the javax.servlet.ServletConfig interface, which allows the
servlet to access initialization parameters from the web
application.
2) The service() method is invoked upon each request after
its initialization. Each request is serviced in its own
separate thread. The web container calls the service()
method of the servlet for every request. The service()
method determines the kind of request being made and
dispatches it to an appropriate method to handle the
request.
3) The destroy() method is invoked when the servlet object
should be destroyed. It releases the resources being held
Servlet Example by implementing
Servlet interface
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;

/**
* Servlet implementation class ServInt
*/
@WebServlet("/ServInt")
public class ServInt implements Servlet {
private static final long serialVersionUID = 1L;
private ServletConfig config = null;

/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
this.config=config;
System.out.println("servlet is initialized");
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
System.out.println("servlet is destroyed");
}

/**
* @see Servlet#getServletConfig()
*/
public ServletConfig getServletConfig() {
return config;
}

/**
* @see Servlet#getServletInfo()
*/
public String getServletInfo() {
return "copyright 2015-2020";
}

/**
* @see HttpServlet#service(HttpServletRequest request,
HttpServletResponse response)
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");

PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}

}
Servlet Example by implementing
Servlet interface
Two abstract classes of the servlet
packages
• Implements the interface Servlet
– GenericServlet class (from package javax.servlet)
– HttpServlet class (from package javax.servlet.http)
• These classes provide default implementation
of all the Servlet methods
• Most servlets extend either GenericServlet or
HttpServlet and overrides some or all of their
methods
Two abstract classes of the servlet
packages
• HttpServlet class defines enhanced processing
capabilities for servlets that extend the
functionality of a Web server
• The key method in every servlet is service,
which receives both a ServletRequest object
and a ServletResponse object
Two abstract classes of the servlet
packages
• These objects provides access to input and
output streams that allow the servlet to read
data from the client and send data to the client
• These streams can be either byte based or
character based
• If problems occur during the execution of a
servlet, either ServletExceptions or IOExceptions
are thrown to indicate the problem
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.
• GenericServlet class can handle any type of
request so it is protocol-independent.
GenericServlet class
• A generic servlet can be by inheriting the
GenericServlet class and providing the
implementation of the service method.
Methods of GenericServlet class
• public void init(ServletConfig config) is used to
initialize the servlet.
• public abstract void service(ServletRequest
request, ServletResponse response) provides
service for the incoming request. It is invoked
at each time when user requests for a servlet.
• public void destroy() is invoked only once
throughout the life cycle and indicates that
servlet is being destroyed.
Methods of GenericServlet class
• public ServletConfig getServletConfig() returns
the object of ServletConfig.
• public String getServletInfo() returns
information about servlet such as writer,
copyright, version etc.
• public void init() it is a convenient method for
the servlet programmers, now there is no
need to call super.init(config)
Methods of GenericServlet class
• public ServletContext getServletContext()
returns the object of ServletContext.
• public String getInitParameter(String name)
returns the parameter value for the given
parameter name.
• public Enumeration getInitParameterNames()
returns all the parameters defined in the
web.xml file.
Methods of GenericServlet class
• public String getServletName() returns the
name of the servlet object.
• public void log(String msg) writes the given
message in the servlet log file.
• public void log(String msg,Throwable t) writes
the explanatory message in the servlet log file
and a stack trace.
import java.io.*;
Servlet Example by inheriting the
import javax.servlet.*;
import javax.servlet.ServletException;
GenericServlet class
import javax.servlet.annotation.WebServlet;
/**
* Servlet implementation class GenServ
*/
@WebServlet("/GenServ")
public class GenServ extends GenericServlet {
private static final long serialVersionUID = 1L;
/**
* @see GenerixServlet#service(ServletRequest request,
ServletResponse response)
*/
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");

PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Servlet Example by inheriting the
GenericServlet class
HttpServlet class
• The HttpServlet class extends the
GenericServlet class and implements
Serializable interface.
• It provides http specific methods such as
doGet, doPost, doHead, doTrace etc.
HttpServlet Class
• Web-based servlets typically extend class
HttpServlet
• Class HttpServlet overrides method service to
distinguish between the typical requests
received from a client browser
• The two most common HTTP request types
(also known as request methods) are
– get
– post
HttpServlet Class
• A get request gets (or retrieves) information
from the server
– Common uses of get requests are to retrieve an
HTML document or image
• A post request posts (or sends) data to a
server
– Common uses of post requests typically sends
information, such as authentication information or
data from a form that gathers user input to a
server
HttpServlet Class
• Class HttpServlet defines methods doGet and
doPost to respond to get and post requests
from a client, respectively
• These methods are called by method service,
which is called when a request arrives at the
server
• Method service first determines the request
the request type, then calls the appropriate
method for handling such a request
HttpServlet Class
• Methods doGet and doPost receive as arguments
an HttpServeletRequest object and an
HttpServletResponse object that enable
interaction between the client and the server
• The methods of HttpServletRequest make it
easier to access the data supplied as part of the
request
• The HttpServletResponse methods make it easy
to return the servlet’s results to the web client
Methods of HttpServlet class
• public void service(ServletRequest
req,ServletResponse res) dispatches the request
to the protected service method by converting
the request and response object into http type.
• protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request
from the service method, and dispatches the
request to the doXXX() method depending on the
incoming http request type.
Methods of HttpServlet class
• protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET
request. It is invoked by the web container.
• protected void doPost(HttpServletRequest
req, HttpServletResponse res) handles the
POST request. It is invoked by the web
container.
Methods of HttpServlet class
• protected void doHead(HttpServletRequest
req, HttpServletResponse res) handles the
HEAD request. It is invoked by the web
container.
• protected void doOptions(HttpServletRequest
req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web
container.
Methods of HttpServlet class
• protected void doPut(HttpServletRequest req,
HttpServletResponse res) handles the PUT
request. It is invoked by the web container.
• protected void doTrace(HttpServletRequest
req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web
container.
Methods of HttpServlet class
• protected void doDelete(HttpServletRequest
req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web
container.
• protected long
getLastModified(HttpServletRequest req)
returns the time when HttpServletRequest
was last modified since midnight January 1,
1970 GMT.
Other Methods of class HttpServlet
Method Description
doDelete Called in response to an HTTP delete request. Such a request is normally
used to delete a file from a server. This may not be available on some
servers, because of its inherent security risks (eg: client could delete a file
that is critical to the execution of the server or an application)
doHead Called in response to an HTTP head request. Such a request is normally
used when the client only wants the headers of a response, such as content
type and content length of the response
doOptions Called in response to an HTTP options request. This return informs to the
client indicating the HTTP options supported by the server, such as the
version of HTTP (1.0 or 1.1) and the request methods the server supports
goPut Called in response to an HTTP put request. Such a request is normally used
to store a file on the server. This may not be available on some servers,
because of its inherent security risks(eg: the client could place an
executable application on the server, which, if executed, could damage the
server – perhaps by deleting critical files or occupying resources
Other methods of class HttpServlet
Method Description
doTrace Called in response to an HTTP trace request. Such a request is normally
used for debugging. The implementation of this method automatically
returns an HTML document to the client containing the request header
information (data sent by the browser as part of the request

These methods receive parameters of type


HttpServletRequest and HttpServletResponse and
return void. However, they are not frequently used.
HttpServletRequest Interface
• Every call to doGet or doPost for an
HttpServlet receives an object that
implements interface HttpServletRequest
• The web server that executes the servlet
creates an HttpServletRequest object and
passes this to the servlet’s service method
• This object contains the request from the
client
HttpServletRequest Interface
• A variety of methods are provided to enable
the servlet are proivded to enable the servlet
to process the client’s request
• Some of these methods are from interface
ServletRequest – the interface that
HttpSevletRequest extends
• Refer Oracle documentation for a complete
list of methods
Some methods of interface
HttpServletRequest
Method Description
String getParameter(String name) Obtains the value of a parameter sent to the servlet as
part of a get or post request. The name argument
represents the parameter name
Enumeration getParameterNames() Returns the names of all the parameters sent to the
servlet as part of a post request
String[] getParameterValues(String For a parameter with multiple values, this method
name) returns an array of strings containing the values for a
specified servlet parameter
Cookie[] getCookies() Returns an array of Cookie objects stored on the client
by the server. Cookie objects can be used to uniquely
identify clients to the servlet
HttpSession getSession(boolean Return an HttpSession object associated with the
create) client’s current browsing session. This method can
create an HttpSession object(true argument) if one does
not already exist for the client. HttpSession objects are
used in similar ways to Cookies for uniquely identifying
clients
HttpServletResponse Interface
• Every call to doGet or doPost for an
HttpServlet receives an object that
implements interface HttpServletResponse
• The web server that executes the servlet
creates an HttpServletResponse object and
passes it to servlet’s service method (which, in
turn, passes it to doGet or doPost)
HttpServletResponse Interface
• This object provides a variety of methods that
enable the servlet to formulate the response
to the client
• Some of these methods are from interface
ServletResponse – the interface that
HttpServletResponse extends
• Refer Oracle documentation for a complete
list of methods
Some methods of interface
HttpServletResponse
Method Description
Void addCookie(Cookie cookie) Used to add a cookie to the header of the response to
the client. The Cookie’s maximum age and whether
Cookie’s are enabled on the client determine if
Cookies are stored on the client
ServletOutputStream Obtains a byte-based output stream for sending
getOutputStream() binary data to the client
PrintWriter getWriter() Obtains a character-based output dtream for sending
text data to the client
Void setContentType(string type) Specifies the MIME type of the response to the
browser. The MIME type helps the browser determine
how to display the data (or possibly what other
application to execute to process the data). For
example, MIME type “text/html” indicates that the
response is an HTML document, so the browser
displays the HTML page
Life Cycle of a Servlet (Servlet Life
Cycle)
• The web container maintains the life cycle of a
servlet instance.
• The life cycle of the servlet is as follows:
– Servlet class is loaded.
– Servlet instance is created.
– init method is invoked.
– service method is invoked.
– destroy method is invoked.
Servlet Life Cycle
1. Load servlet
2. Create servlet instance
3. Call the init() method

4. Call the service() method


READY

5. Call the destroy() method


Servlet Life Cycle
• As displayed in the above diagram, there are
three states of a servlet: new, ready and end.
• The servlet is in new state if servlet instance is
created.
• After invoking the init() method, Servlet comes in
the ready state.
• In the ready state, servlet performs all the tasks.
• When the web container invokes the destroy()
method, it shifts to the end state.
Servlet Life Cycle
• Servlet class is loaded
– The classloader is responsible to load the servlet
class.
– The servlet class is loaded when the first request
for the servlet is received by the web container.
• Servlet instance is created
– The web container creates the instance of a
servlet after loading the servlet class.
– The servlet instance is created only once in the
servlet life cycle.
Servlet Life Cycle
• init method is invoked
– The web container calls the init method only once
after creating the servlet instance.
– The init method is used to initialize the servlet.
– It is the life cycle method of the
javax.servlet.Servlet interface.
– Syntax of the init method is given below:
• public void init(ServletConfig config) throws ServletExc
eption
Servlet Life Cycle
• service method is invoked
– 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 as described above then calls the service
method.
– If servlet is initialized, it calls the service method.
– Notice that servlet is initialized only once.
– The syntax of the service method of the Servlet
interface is given below:
• public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
Servlet Life Cycle
• destroy method is invoked
– 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()
Servlet’s Life Cycle
• The cycle begins when the servlet container
loads the servlet into memory – normally, in
response to the first request that the servlet
receives
• Before the servlet can handle that request,
the servlet container invokes the servlet’s init
method
• After init completes execution, the servlet can
respond to its first request
Servlet’s Life Cycle
• All requests are handled by a servlet’s service
method, which receives the request,
processes the request and sends a response to
the client
• During a servlet’s life cycle, method service is
called once per request
Servlet’s Life Cycle
• Each new request typically results in a new
thread of execution (created by the servlet
container) in which method service executes
• When the servlet container terminates the
servlet, the servlet’s destroy method is called
to release servlet resources
Steps to create a servlet example
• There are given 6 steps to create a servlet
example.
• These steps are required for all the servers.
– Create a directory structure
– Create a Servlet
– Compile the Servlet
– Create a deployment descriptor
– Start the server and deploy the project
– Access the servlet
Create a directory structures
• 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.
Web-app
(Context-root)

WEB-INF
Classes Class files
web.xml
HTML
lib
Static resources (eg: images, css etc.
Create a Servlet
• There are three ways to create the servlet.
– By implementing the Servlet interface
– By inheriting the GenericServlet class
– 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.
Create a Servlet
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;

/**
* Servlet implementation class DemoServlet
*/
@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
Create a Servlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");//setting the content type
PrintWriter pw=response.getWriter();//get the stream to write the
data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}
}
Create a Servlet
Compile the servlet
• For compiling the Servlet, jar file is required to
be loaded.
• Different Servers provide different jar files:

Jar file Server


1) servlet-api.jar Apache Tomacat
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
Compile the servlet
• Two ways to load the jar file
– set classpath
– paste the jar file in JRE/lib/ext folder
• Put the java file in any folder.
• After compiling the java file, paste the class
file of servlet in WEB-INF/classes directory.
Create the deployment descriptor
(web.xml file)
• 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
and Pull.
web.xml
• There are many elements in the web.xml file.
• Here is given some necessary elements to run
the simple servlet program.
<web-app>

<servlet>
<servlet-name>ExampleServ</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ExampleServ</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>
Description of the elements of
web.xml file
• <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.
• <servlet-mapping> is sub element of <web-app>. It is
used to map the servlet.
• <url-pattern> is sub element of <servlet-mapping>.
This pattern is used at client side to invoke the servlet.
Start the Server and deploy the
project
• To start Apache Tomcat server, double click on
the startup.bat file under apache-tomcat/bin
directory.
• One Time Configuration for Apache Tomcat
Server
– You need to perform 2 tasks:
• set JAVA_HOME or JRE_HOME in environment variable (It is
required to start server).
• Change the port number of tomcat (optional). It is required
if another server is running on same port (8080).
Start the Server and deploy the
project
• 1) How to set JAVA_HOME in environment
variable?
• To start Apache Tomcat server JAVA_HOME
and JRE_HOME must be set in Environment
variables.
– Go to My Computer properties -> Click on
advanced tab then environment variables -> Click
on the new tab of user variable -> Write
JAVA_HOME in variable name and paste the path
of jdk folder in variable value -> ok -> ok -> ok.
Start the Server and deploy the
project
• After setting the JAVA_HOME double click on
the startup.bat file in apache tomcat/bin.
– Note: There are two types of tomcat available:
• Apache tomcat that needs to extract only (no
need to install)
• Apache tomcat that needs to install
Start the Server and deploy the
project
• 2) How to change port number of apache
tomcat
– Changing the port number is required if there is
another server running on the same system with
same port number.
– Suppose you have installed oracle, you need to
change the port number of apache tomcat
because both have the default port number 8080.
Start the Server and deploy the
project
• Open server.xml file in notepad.
• It is located inside the apache-tomcat/conf
directory .
• Change the Connector port = 8080 and
replace 8080 by any four digit number instead
of 8080.
• Let us replace it by 9999 and save this file.
How to deploy the servlet project?
• Copy the project and paste it in the webapps
folder under apache tomcat.
• But there are several ways to deploy the project.
• They are as follows:
– By copying the context(project) folder into the
webapps directory
– By copying the war folder into the webapps directory
– By selecting the folder path from the server
– By selecting the war file from the server
How to deploy the servlet project?
• Here, we are using the first approach.
• You can also create war file, and paste it inside
the webapps directory.
• To do so, you need to use jar tool to create the
war file.
• Go inside the project directory (before the
WEB-INF), then write:
– projectfolder> jar cvf myproject.war *
How to deploy the servlet project?
• Creating war file has an advantage that
moving the project from one location to
another takes less time.
How to access the servlet?
• Open browser and write
– http://hostname:portno/contextroot/urlpatternof
servlet.
• For example:
– http://localhost:9999/demo/welcome
Servlets

BY IMPLEMENTING SERVLET
INTERFACE
index.html
<a href="hello">Invoke Generic Servlet</a>
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>
First.java
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");
First.java
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

}
Output
Output
Servlets

BY INHERITING GENERIC SERVLET


CLASS
index.html

<a href="hello">Invoke Generic Servlet</a>


web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>
First.java
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>");

}
}
Output
Output
Servlets

BY INHERITING HTTPSERVLET CLASS


index.html
<html>

<body>

<form action="/example/welcome" method="get">


Enter your name<input type="text"

name="name"/><br>

<input type="submit" value="login"/>


</form>
</body>
</html>
web.xml
<web-app>

<servlet>
<servlet-name>ExampleServ</servlet-name>
<servlet-class>DemoServ</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ExampleServ</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ 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");
pw.println("Welcome "+name);
}}
Output
Output
Examples
• Handling HTTP get Requests
• Handling HTTP get Requests Containing Data
• Handling HTTP post Requests
• Redirecting Requests to Other Resources
Java Servlets

EXAMPLE 1: HANDLING HTTP GET


REQUESTS
Handling HTTP get Requests
• The primary purpose of HTTP get request is to
retrieve the content (HTML or XHTML
document eg: Web page) of a specified URL

Request -
Get HTML
Get HTML Document
Welcome servlet
Document
Response –
Generate a
dynamic XHTML
document
WelcomeServlet.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- WelcomeServlet.html -->

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Handling an HTTP Get Request</title>
</head>

<body>
<form action = "/jhtp5/welcome1" method = "get">

<p><label>Click the button to invoke the servlet


<input type = "submit" value = "Get HTML Document" />
</label></p>

</form>
</body>
</html>
WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class WelcomeServlet extends HttpServlet {

// process "get" requests from clients


protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

// send XHTML page to client

// start XHTML document


out.println( "<?xml version = \"1.0\"?>" );

out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +


"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
WelcomeServlet.java contd…

out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

// head section of document


out.println( "<head>" );
out.println( "<title>A Simple Servlet Example</title>" );
out.println( "</head>" );

// body section of document


out.println( "<body>" );
out.println( "<h1>Welcome to Servlets!</h1>" );
out.println( "</body>" );

// end XHTML document


out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
Deployment descriptor – web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<!-- General description of your Web application -->


<display-name>
Java How to Program Servlet
</display-name>

<description>
This is the Web application in which we
demonstrate our JSP and Servlet examples.
</description>
Deployment descriptor – web.xml
<!-- Servlet definitions -->
contd…
<servlet>
<servlet-name>welcome1</servlet-name>

<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet
</servlet-class>
</servlet>

<!-- Servlet mappings -->


<servlet-mapping>
<servlet-name>welcome1</servlet-name>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>

</web-app>
Steps to follow
• (1) Code WelcomeServlet.html, WelcomeServlet.java and
web.xml (deployment descriptor)
• (2) Compile the WelcomeServlet.java using relevant path
(where servlet-api.jar is located in Tomcat server)
– Eg: javac -classpath ".;G:\Univotec\Enterprise
Java\Tomcat\apache-tomcat-8.0.0-RC10-windows-x64\apache-
tomcat-8.0.0-RC10\lib\servlet-api.jar" WelcomeServlet.java
• (3) Place them in relevant directories of the Tomcat server
• (3) Start Tomcat server
• Type the following URL in the web browser
– http://localhost:8080/jhtp5/servlets/WelcomeServlet.html
Client request page
Response from the Servlet
Java Servlets

EXAMPLE 2: HANDLING HTTP GET


REQUESTS CONTAINING DATA
WelcomeServlet2.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Processing get requests with data</title>
</head>

<body>
<form action = "/jhtp5/welcome2" method = "get">

<p><label>
Type your first name and press the Submit button
<br /><input type = "text" name = "firstname" />
<input type = "submit" value = "Submit" />
</p></label>

</form>
</body>
</html>
WelcomeServlet2.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class WelcomeServlet2 extends HttpServlet {

// process "get" request from client


protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
String firstName = request.getParameter( "firstname" );

response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

// send XHTML document to client

// start XHTML document


out.println( "<?xml version = \"1.0\"?>" );
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

// head section of document


out.println( "<head>" );
out.println(
"<title>Processing get requests with data</title>" );
out.println( "</head>" );

// body section of document


out.println( "<body>" );
out.println( "<h1>Hello " + firstName + ",<br />" );
out.println( "Welcome to Servlets!</h1>" );
out.println( "</body>" );

// end XHTML document


out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<!-- General description of your Web application -->


<display-name>
Java How to Program JSP and Servlet Chapter Examples
</display-name>

<description>
This is the Web application in which we
demonstrate our JSP and Servlet examples.
</description>

<!-- Servlet definitions -->


<servlet>
<servlet-name>welcome1</servlet-name>
<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet
</servlet-class>
</servlet>

<servlet>
<servlet-name>welcome2</servlet-name>

<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet2
</servlet-class>
</servlet>
<!-- Servlet mappings -->
<servlet-mapping>
<servlet-name>welcome1</servlet-name>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>welcome2</servlet-name>
<url-pattern>/welcome2</url-pattern>
</servlet-mapping>

</web-app>
Client request page
Response from the Servlet
Java Servlets

EXAMPLE 3: HANDLING HTTP POST


REQUESTS
WelcomeServlet3.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Handling an HTTP Post Request with Data</title>
</head>

<body>
<form action = "/jhtp5/welcome3" method = "post">

<p><label>
Type your first name and press the Submit button
<br /><input type = "text" name = "firstname" />
<input type = "submit" value = "Submit" />
</label></p>

</form>
</body>
</html>
WelcomeServlet3.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class WelcomeServlet3 extends HttpServlet {

// process "post" request from client


protected void doPost( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
String firstName = request.getParameter( "firstname" );

response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

// send XHTML page to client

// start XHTML document


out.println( "<?xml version = \"1.0\"?>" );
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

// head section of document


out.println( "<head>" );
out.println(
"<title>Processing post requests with data</title>" );
out.println( "</head>" );

// body section of document


out.println( "<body>" );
out.println( "<h1>Hello " + firstName + ",<br />" );
out.println( "Welcome to Servlets!</h1>" );
out.println( "</body>" );

// end XHTML document


out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<!-- General description of your Web application -->


<display-name>
Java How to Program JSP and Servlet Chapter Examples
</display-name>

<description>
This is the Web application in which we
demonstrate our JSP and Servlet examples.
</description>

<!-- Servlet definitions -->


<servlet>
<servlet-name>welcome1</servlet-name>
<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet
</servlet-class>
</servlet>

<servlet>
<servlet-name>welcome2</servlet-name>

<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet2
</servlet-class>
</servlet>

<servlet>
<servlet-name>welcome3</servlet-name>
<description>
A simple servlet that handles an HTTP post request.
</description>

<servlet-class>
WelcomeServlet3
</servlet-class>
</servlet>

<!-- Servlet mappings -->


<servlet-mapping>
<servlet-name>welcome1</servlet-name>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>welcome2</servlet-name>
<url-pattern>/welcome2</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>welcome3</servlet-name>
<url-pattern>/welcome3</url-pattern>
</servlet-mapping>
</web-app>
Client request page
Response from the Servlet
Java Servlets

EXAMPLE 4: REDIRECTING REQUESTS


TO OTHER RESOURCES
RedirectServlet.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Redirecting a Request to Another Site</title>
</head>

<body>
<p>Click a link to be redirected to the appropriate page</p>
<p>
<a href = "/jhtp5/redirect?page=amazon">
www.amazon.com</a><br />
<a href = "/jhtp5/redirect?page=welcome1">
Welcome servlet</a>
</p>
</body>
</html>
RedirectServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class RedirectServlet extends HttpServlet {

// process "get" request from client


protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
String location = request.getParameter( "page" );

if ( location != null )

if ( location.equals( "amazon" ) )
response.sendRedirect( "http://www.amazon.com" );
else
if ( location.equals( "welcome1" ) )
response.sendRedirect( "welcome1" );
// code that executes only if this servlet
// does not redirect the user to another page

response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

// start XHTML document


out.println( "<?xml version = \"1.0\"?>" );

out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +


"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

// head section of document


out.println( "<head>" );
out.println( "<title>Invalid page</title>" );
out.println( "</head>" );

// body section of document


out.println( "<body>" );
out.println( "<h1>Invalid page requested</h1>" );
out.println( "<p><a href = " +
"\"servlets/RedirectServlet.html\">" );
out.println( "Click here to choose again</a></p>" );
out.println( "</body>" );

// end XHTML document


out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<!-- General description of your Web application -->


<display-name>
Java How to Program JSP and Servlet Chapter Examples
</display-name>

<description>
This is the Web application in which we
demonstrate our JSP and Servlet examples.
</description>

<!-- Servlet definitions -->


<servlet>
<servlet-name>welcome1</servlet-name>
<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet
</servlet-class>
</servlet>

<servlet>
<servlet-name>welcome2</servlet-name>

<description>
A simple servlet that handles an HTTP get request.
</description>

<servlet-class>
WelcomeServlet2
</servlet-class>
</servlet>

<servlet>
<servlet-name>welcome3</servlet-name>
<description>
A simple servlet that handles an HTTP post request.
</description>

<servlet-class>
WelcomeServlet3
</servlet-class>
</servlet>

<!-- Servlet mappings -->


<servlet-mapping>
<servlet-name>welcome1</servlet-name>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>welcome2</servlet-name>
<url-pattern>/welcome2</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>welcome3</servlet-name>
<url-pattern>/welcome3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
</servlet-mapping>

</web-app>
Client request page
Response from the Servlet
Response from the Servlet
Using Eclipse

CREATING SERVLET EXAMPLE IN


ECLIPSE
Creating Servlet Example in Eclipse
• Download the eclipse ide for JavaEE
developers
• Steps to follow to create the first servlet
example.
– Create a Dynamic web project
– create a servlet
– add servlet-api.jar file
– Run the servlet
Create the dynamic web project
Create the dynamic web project
Create the dynamic web project
Create the dynamic web project
Create the dynamic web project
Create the servlet in eclipse IDE
Create the servlet in eclipse IDE
Create the servlet in eclipse IDE
Create the servlet in eclipse IDE
Create the servlet in eclipse IDE
add jar file in eclipse IDE
add jar file in eclipse IDE
add jar file in eclipse IDE
add jar file in eclipse IDE
add jar file in eclipse IDE
add jar file in eclipse IDE
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class Hello
*/
@WebServlet("/Hello")
public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;
public Hello() {}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
}

}
Start the server and deploy the
project
Start the server and deploy the
project
Start the server and deploy the
project
Start the server and deploy the
project
Start the server and deploy the
project
Start the server and deploy the
project
Start the server and deploy the
project

You might also like