Day02 Slide 4 Servlet
Day02 Slide 4 Servlet
Objectives
◼Servlet hierarchy
◼Servlet Life cycle
◼HttpServlet
◼HttpServletRequest
◼HttpServletResponse
◼Servlet mapping
◼Servlets collaboration
4/15/2022 2/41
What a Servlet is
• Servlets are small Java programs that run on a
Web server and help to build dynamic Web pages.
• Servlets receive and respond to requests from Web
clients, usually across HTTP, the HyperText
Transfer Protocol.
4/15/2022 3/41
What a Servlet is
• Java Servlet technology was created as a portable
way to provide dynamic, user-oriented content.
• Because the servlet is running on the server side, it
does not require any Java-support from Web
browser
• Servlet is multi-thread
• Controller
4/15/2022 4/41
Using Servlet in
◼ Read HTML form data, use cookies and
session
◼ Browser send the request to the server, Java
servlet will execute and
◼ generate HTML content send back to the Web
browser as the response
4/15/2022 5/24
What a Servlet is
• Servlet is multi-thread
4/15/2022 6/41
The servlet Code
4/15/2022 7/24
Adding Servlet to the web.xml file
◼ web.xml defines mappings between URL paths and
the servlets that handle requests with those paths
◼ The web server uses this configuration to identify the
servlet to handle a given request and call the class
method that corresponds to the request method (e.g.
the doGet() method for HTTP GET requests).
4/15/2022 8/24
Adding Servlet to the web.xml file
◼ To map a URL to a servlet, you declare the servlet with the
<servlet> element, then define a mapping from a URL path to
a servlet declaration with the <servlet-mapping> element.
◼ The <servlet> element declares the servlet, including a name
used to refer to the servlet by other elements in the file, the
class to use for the servlet, and initialization parameters.
4/15/2022 9/24
Comparing JSP and Servlet
4/15/2022 10/24
Best Practice
4/15/2022 11/24
Hierarchy of Servlet class
• The javax.servlet
package provides interfaces
and classes for writing servlets
4/15/2022 12/24
The Servlet interface
◼ At the heart of servlet architecture is the
interface javax.servlet.Servlet.
◼ It provides the framework for all servlets.
◼ The Servlet interface defines five methods.
The three most important are as follows:
◼ init() method—Initializes a servlet
◼ service() method—Receives and responds to client
requests
◼ destroy() method—Performs cleanup
◼ All servlets must implement this interface, either
directly or through inheritance.
4/15/2022 13/41
The servlet container
4/15/2022 14/41
The Servlet Life Cycle
init
service
destroy
4/15/2022 15/41
Servlet life cycle
◼ The init() method is where the servlet's
life cycle begins.
◼ It is called by the server immediately after the
servlet is instantiated.
◼ It is called only once.
◼ public void init(ServletConfig config) throws
ServletException;
◼ In the init() method, the servlet creates and
initializes any resources, including data members,
that it will be using while handling requests.
4/15/2022 16/41
Servlet life cycle
◼ The service() method handles all
requests sent by a client.
◼ The entry point for executing application logic
in a servlet
◼ It cannot start servicing requests until the
init() method has been executed.
◼ The service() method implements a
request and response paradigm.
◼ We should never implement this method
directly if extending from HttpServlet
4/15/2022 17/41
Servlet life cycle
◼ The destroy() method signifies the end of a
servlet's life.
◼ When a service is being shut down, it calls the servlet's
destroy() method.
◼ This is where any resources that were created in the init()
method will be cleaned up.
◼ If you have an open database connection, you should close it
here.
◼ This is also a good place to save any persistent information that
will be used the next time the servlet is loaded.
◼ The getServletConfig() method returns
the servlet's ServletConfig object, which
contains the servlet's startup configuration and
initialization parameters.
4/15/2022 18
The ServletRequest
◼ ServletRequest encapsulate information about the client's
request includes: parameter name/value pairs, attributes, and an
input stream.
◼ getAttribute(String name) returns value of
the object keyed by the name for the current request.
◼ getParameter(String name) method returns
the value of the requested parameter.
◼ If the parameter has or could have more than one
value, use the getParameterValues() method.
◼ getRemoteAddress() method returns a String
representing the IP address of the client sending the
request.
4/15/2022 19/41
The ServletResponse
◼ ServletResponse sends MIME data back to the client from the
servlet's service method.
◼ getWriter() method returns a print writer used for
writing formatted text to the response object.
◼ getOutputStream() method returns an output
stream used for writing binary data to the response.
◼ setContentType() method sets the content type
of the current response.
◼ This method must be called before calling the getWriter()
or getOutputStream() methods.
4/15/2022 20/41
Servlet Demo 02
◼ Reading Form with ServletReading Form with Servlet
4/15/2022 21/24
Servlet Demo 02
4/15/2022 22/24
Servlet Demo 02
4/15/2022 23/24
Servlet Demo 02
4/15/2022 24/24
Result
4/15/2022 25/24
4/15/2022 26/24
doPost() method
4/15/2022 27/24
doPost() method
4/15/2022 28/24
Sending data with GET method
4/15/2022 29/24
Sending data with POST method
4/15/2022 30/24
Get vs Post
4/15/2022 31/24
4/15/2022 32/24
Reading Configuration Parameters
4/15/2022 33/24
Reading Configuration Parameters
4/15/2022 34/24
Reading Configuration Parameters
4/15/2022 35/24
HttpServlet
◼ The HttpServlet class has already implemented the
service() method.
protected void service(HttpServletRequest req,
HttpServletResponse resp)throws ServletException, IOException;
◼ When the HttpServlet.service() method is
invoked, it reads the method type stored in the request
and determines which method to invoke based upon this
value.
◼ If the method type is GET, it will call doGet(). If the method
type is POST, it will call doPost().
◼ These are the methods that you will want to override
◼ Typically, we should not override the service() method, but the
doPost() and/or doGet() method
4/15/2022 36/41
HttpServlet
4/15/2022 37/41
HttpServlet Class
• The protocol defines a set of text-based request messages
called HTTP ‘methods’ implemented in HttpServlet class:
◼ doGet Called by the server (via the service method)to allow a servlet to
handle a GET request
◼ doHead Receives an HTTP HEAD request from the protected
service method and handles the request
◼ doPost called by the server to allow a servlet to handle post
request
◼ doPut Called by the server (via the service method) to allow a
servlet to handle a PUT request
◼ doDelete Called by the server (via the service method) to allow a
servlet to handle a DELETE request
◼ doTrace Called by the server (via the service method) to allow a
servlet to handle a TRACE request
◼ doOptions Called by the server (via the service method) to allow a
servlet to handle a OPTIONS request
4/15/2022 38/41
The HttpServletRequest
◼ HttpServletRequest provides the HttpServlet.service()
to access HTTP header information sent by the client.
◼ getQueryString() method returns the query string from the
request.
◼ getSession(true) method returns the session associated
with the request. If there is no valid session and the boolean
parameter passed in is true, then it will create a new session.
◼ getRemoteUser() method returns the name of the user
making the request. If the name is not available, null is returned.
◼ getMethod() method returns the HTTP method used by the
client request.
◼ setAttribute(name, object) save object into request with name
4/15/2022
39/41
The HttpServletResponse
◼ HttpServletResponse
◼ encodeURL() method encodes the passed-in
String and returns it. If no changes are
necessary, then it simply returns the String.
◼ sendError(int er, String msg) method
sends an error to the client in the response
object. The error consists of the int status code
and a String message.
◼ sendRedirect(url) method redirects the
client to the passed-in URL, which must be an
absolute URL.
4/15/2022 40/41
Servlet init parameter
◼ Init parameters of a servlet can help to specify important
aspects that are going to be handled during requests
service.
◼ Semester code for a servlet to retrieve student’s timetable
◼ Declare in web.xml for servlet
◼ String semCode=getInitParameter(“semester”);
4/15/2022 41/41
Servlet mapping-Invoke a Servlet
◼ There are two ways to invoke a servlet.
◼ Servlet mapping in web.xml: calling by url-pattern
4/15/2022 42/41
A Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
4/15/2022 43/41
Servlet Collaboration
◼ A servlet can receive a request from client and
delegates the processing to another servlet.
◼ There are 2 solutions for this collaboration:
◼ Using servlet chaining:
◼ configure the servlet container to chain the servlet;
◼ not supported by servlet API specification
◼ Using Request Dispatching
◼ Allow a servlet to dispatch a request to another
servlet/jsp for generating the response
◼ The RequestDispatcher used for this purpose
4/15/2022 44/41
RequestDispatcher
◼ A servlet obtains a RequestDispatcher object
for a resource by calling:
◼ ServletContext.getRequestDispatcher(String URLpath)
◼ ServletRequest. getRequestDispatcher(String URLpath)
◼ ServletContext.getNameDispatcher(String name)
◼ void forward(request,response)
✓ Forwards a request from a servlet to another resource
✓ The request and response parameters must be the same
objects as were passed to the calling servlet
◼ void include(request,response)
✓ Includes the content of a resource (servlet, JSP page, HTML
file) in the response
4/15/2022 45/41
Summary
◼ Servlets concept
◼ Servlets hierarchy structure
◼ Servlet life cycle
◼ HttpServlet
◼ HttpServletRequest
◼ HttpServletResponse
◼ Servlet Init parameter
◼ Servlet mapping
◼ Servlet Collaboration
4/15/2022 46/41
Constructive question
◼ How many servlet instance are instantiated to
serve many request from multi client?
◼ When the servlet's init() method is invoked?
◼ A web application allows users to log in with
different roles. Try to come up the solution to
meet this requirement that is most convenient
for users
◼ Write a single servlet that responds to user
login requests with no support components
4/15/2022 47/24