JAVA SERVLET
PROGRAMMING
Instructor: DieuNT1
©FPT SOFTWARE - Corporate Training Center - Internal Use 1
Learning Goals
Can use
Servlet to
develop web
application
Understand
Servlet
©FPT SOFTWARE - Corporate Training Center - Internal Use 2
Table Content
◊ Introduction to Servlet
◊ Servlet API
◊ Servlet Request and Response
◊ Servlet Context
◊ Create servlet in Eclipse IDE
©FPT SOFTWARE - Corporate Training Center - Internal Use 3
Section 1
INTRODUCTION TO SERVLET
©FPT SOFTWARE - Corporate Training Center - Internal Use 4
Servlet Overview
Java Servlets are programs that run on a Web or Application
server and act as a middle layer between a request coming
from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Performance is significantly better.
Servlets are platform-independent because they are written in
Java.
©FPT SOFTWARE - Corporate Training Center - Internal Use 5
Servlet Architecture
A Servlet is a class, which implements the javax.servlet.Servlet interface.
To write a servlet we need to implement Servlet interface.
Servlet interface can be implemented directly or indirectly by
extending GenericServlet or HttpServlet class.
Purpose of extending the HttpServlet class is to provide the HTTP
specific services to your servlet.
©FPT SOFTWARE - Corporate Training Center - Internal Use 6
Servlet Architecture
©FPT SOFTWARE - Corporate Training Center - Internal Use 7
Servlet Application works
Web container is responsible for managing execution of
servlets and JSP pages or Java EE application:
User sends request for a servlet by clicking a link that has URL to a
servlet.
The container finds the servlet using deployment descriptor and creates
two objects:
• HttpServletRequest
• HttpServletResponse
1 2
©FPT SOFTWARE - Corporate Training Center - Internal Use 8
Servlet Application works
Then the container calls the Servlet's service() method and passes the
request, response objects as arguments.
The service() method, then decides which servlet method, doGet() or
doPost() to call.
3 4
Then the Servlet uses response object to write the response back to the
client. 5 6
©FPT SOFTWARE - Corporate Training Center - Internal Use 9
Servlet Life Cycle
A servlet life cycle can be defined as the entire process from its creation till
the destruction.
The following are the paths followed by a servlet:
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Servlet container provides the execution The Web container manages a servlet by
environment for Servlet. invoking various life cycle methods.
©FPT SOFTWARE - Corporate Training Center - Internal Use 10
Section 2
SERVLET API
©FPT SOFTWARE - Corporate Training Center - Internal Use 11
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.
Method doGet responds to get requests
Retrieve the content of a URL.
Method doPost responds to post requests
Post data from an HTML form to a server-side form handler.
Browsers cache Web pages.
HttpServletRequest and HttpServletResponse objects
Created by the servlet container and passed as an argument to the servlet's
service methods (doGet, doPost, etc.)
HttpServletRequest object contains request from the client,
HttpServletResponse object provides HTTP-specific functionality in sending a
response (access HTTP headers, cookies, etc.)
©FPT SOFTWARE - Corporate Training Center - Internal Use 12
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.
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.
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.
protected void doPut(HttpServletRequest req, HttpServletResponse res)
handles the PUT request. It is invoked by the web container.
©FPT SOFTWARE - Corporate Training Center - Internal Use 13
HttpServlet Class
protected void doTrace(HttpServletRequest req, HttpServletResponse res):
handles the TRACE request. It is invoked by the web container.
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.
©FPT SOFTWARE - Corporate Training Center - Internal Use 14
Section 3
SERVLET REQUEST AND RESPONSE
©FPT SOFTWARE - Corporate Training Center - Internal Use 15
HttpServletRequest
HttpServletRequest interface adds the methods that relates to
the HTTP protocol.
Methods (extension/addition method)
©FPT SOFTWARE - Corporate Training Center - Internal Use 16
HttpServletResponse
HttpServletResponse interface adds the methods that relates
to the HTTP response.
Methods (extension/addition method)
©FPT SOFTWARE - Corporate Training Center - Internal Use 17
RequestDispatcher
RequestDispatcher is an interface, implementation of which
defines an object which can dispatch request to any
resources(such as HTML, Image, JSP, Servlet) on the server.
Methods:
Example:
©FPT SOFTWARE - Corporate Training Center - Internal Use 18
RequestDispatcher
redirection vs request dispatching
The main difference between a redirection and a request
dispatching:
redirection makes the client(browser) create a new request to get to the
resource, the user can see the new URL;
request dispatch get the resource in same request and URL does not
changes.
©FPT SOFTWARE - Corporate Training Center - Internal Use 19
ServletContext
An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration
information from web.xml file.
Servlet Context has 3 main methods:
GetAttribute ()
SetAttribute ()
RemoveAttribute ()
Servlet Context help provides communication between the servlet
Servlet Context can also be used to obtain configuration information
web.xml.
©FPT SOFTWARE - Corporate Training Center - Internal Use 20
ServletContext Example
©FPT SOFTWARE - Corporate Training Center - Internal Use 21
Servlet Context
Sample
We can change the init() method of the SurveyServlet as below:
Then we need to amend the web.xml file to specify the initial
context parameters:
©FPT SOFTWARE - Corporate Training Center - Internal Use 22
Section 4
CREATE SERVLET IN ECLIPSE IDE
©FPT SOFTWARE - Corporate Training Center - Internal Use 23
Steps to create Servlet using Eclipse IDE
Create a Dynamic Web Project, give a name to your project (Ex: SMS_P1)
1
A directory structure of your
Project will be automatically
created by Eclipse IDE.
©FPT SOFTWARE - Corporate Training Center - Internal Use 24
Steps to create Servlet using Eclipse IDE
Create a Servlet class by extends HttpServlet.
Add servlet-api.jar JAR
file to your project
©FPT SOFTWARE - Corporate Training Center - Internal Use 25
Handling HTTP get Requests
Create a Servlet (WelcomeServlet.java):
Import the javax.servlet and javax.servlet.http packages.
Extends HttpServlet to handle HTTP get requests and HTTP
post requests.
doGet
Override method doGet to provide custom get request
processing.
Uses the response object’s setContentType method to specify
the content type of the data to be sent as the response to the
client.
Uses the response object’s getWriter method to obtain a
reference to the PrintWriter object that enables the servlet to
send content to the client.
Create the XHTML document by writing strings with the out
object’s println method.
Closes the output stream, flushes the output buffer and sends the
©FPT SOFTWARE - Corporate Training Center - Internal Use information to the client. 26
Create Deployement Descriptor
1 <!DOCTYPE web-app PUBLIC
Deployment
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> descriptor
4 Element web-app defines the configuration of (web.xml) for
5 <web-app>
each servlet in the Web application and the servlet the Web
6
7 <!-- General description
mapping for each servlet.
of your Web application --> application.
8 <display-name>
Element display-name specifies a name
9 Sample
10 Servlet Examples
that can be displayed to the administrator
11 </display-name> of the server on which the Web
12 application is installed.
13 <description>
Element description specifies a
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
description of the Web application that
16 </description> might be displayed to the administrator of
17 the server.
18 <!-- Servlet definitions -->
19 <servlet> Element servlet describes a servlet. Element servlet-name is the
20 <servlet-name>welcome</servlet-name>
name for the servlet.
21
22 <description> Element description
23 A simple servlet that handles an HTTP get request. specifies a description for this
24 </description>
particular servlet.
25
26 <servlet-class> Element servlet-class specifies
27 atjb.day3.WelcomeServlet compiled servlet’s fully
28 </servlet-class> qualified class name.
29 </servlet>
30
©FPT SOFTWARE - Corporate Training Center - Internal Use 27
Create Deployement Descriptor
31 <!-- Servlet mappings -->
32 <servlet-mapping>
33 <servlet-name>welcome</servlet-name>
Element servlet-mapping
34 <url-pattern>/welcomeServlet</url-pattern>
specifies servlet-name and url-
pattern elements.
35 </servlet-mapping>
36
37 </web-app>
©FPT SOFTWARE - Corporate Training Center - Internal Use 28
Handling HTTP get Requests
Jsp page in which the form’s action invokes WelcomeServlet through the
alias welcome specified in web.xml.
Example: Welcome.jsp
©FPT SOFTWARE - Corporate Training Center - Internal Use 29
Handling HTTP post Requests
HTTP post request
Post data from an HTML form to a server-side form handler
Browsers cache Web pages
Practices time:
Let’s try to see differences between HTTP post and HTTP get requests
Use HTTPServletRequest’s getParameter method() to get param value
©FPT SOFTWARE - Corporate Training Center - Internal Use 30
Practices time
Handling HTTP post Requests sample:
<form action="${pageContext.request.contextPath}/WelcomeServlet?"
method="post">
User Login
©FPT SOFTWARE - Corporate Training Center - Internal Use 31
Summary
Introduction to Servlet
Servlet API
Servlet Request and Response
Servlet Context
Create servlet in Eclipse IDE
©FPT SOFTWARE - Corporate Training Center - Internal Use 32
Thank you
©FPT SOFTWARE - Corporate Training Center - Internal Use 33
33