Java Servlet Technology
Introduction• Servlets are Java programs that run on a
Web server, handle HTTP requests and build Web pages
• Servlet specification versions• [version 1.0] June 1997• [version 2.4] November 2003• [version 2.5] September 2005
J2EE architectureDistributed component-based multi-tier enterprise application model
Servlets in J2EE
Java Servlet - a Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request-response paradigm
What is Servlet?• Java™ objects which are based on servlet
framework and APIs and extend the functionality of a HTTP server
• Mapped to URLs and managed by container with a simple architecture
• Available and running on all major web servers and application servers
• Platform and server independent
A Servlet That Generates Plain Textimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ PrintWriter out = response.getWriter(); out.println("Hello World!“); } ...}
A Servlet That Generates HTMLimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html“); PrintWriter out = response.getWriter(); out.println("<title>Hello World!</title>“); } ...}
Mapping URLs to Servlets• When a request is received by the web container
it must determine which web component should handle the request
• Need to add a servlet definition and a servlet mapping for each servlet to web.xml file<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
URL patterns• Four types of URL patterns
• Exact match:<url-pattern>/dir1/dir2/name</url-pattern>
• Path match:<url-pattern>/dir1/dir2/*</url-pattern>
• Extension match:<url-pattern>*.ext</url-pattern>
• Default resource:<url-pattern>/</url-pattern>
Servlets and JSP - ComparisonJSP is a text-based document capable of returning dynamic content to a client browser
Servlets typically
are used for
returning
non-HTML data
Servlet Request & Response Model
What Does Servlet Do?• Receives client request (mostly in the form of HTTP
request)
• Extract some information from the request
• Do content generation or business logic process (possibly by accessing database, invoking EJBs, etc)
• Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet or JSP page
Requests and Responses• What is a request?
• Information that is sent from client to a server• Who made the request• What user-entered data is sent• Which HTTP headers are sent
• What is a response?• Information that is sent to client from a server
• Text (html, plain) or binary (image) data• HTTP headers, cookies, etc
Servlet Interfaces & Classes
interfaces
classes
Servlet Life Cycle• The life cycle of a servlet is controlled by the
container• When a HTTP request is mapped to a servlet, the
container performs the following steps
1. If an instance of the servlet does not exist, the web containera. Loads the servlet classb. Creates an instance of the servlet classc. Initializes the servlet instance by calling the init
method2. Invokes the service method, passing request and
response objects
Servlet Life Cycle Methods
Servlet Life Cycle Methods• Invoked by container
• container controls life cycle of a servlet
• Defined in• javax.servlet.GenericServlet class
• init()• destroy()• service() - this is an abstract method
• javax.servlet.http.HttpServlet class• doGet(), doPost(), doXxx()• service() - implementation
init() & destroy()• init()
• Invoked once when the servlet is first instantiated• Not called for each request• Perform any set-up in this method
• setting up a database connection
• destroy()• Invoked before servlet instance is removed• Not called after each request• Perform any clean-up
• closing a previously created database connection
Example: init()public class CatalogServlet extends HttpServlet { private BookDB bookDB; // Perform any one-time operation for the servlet, // like getting database connection object. // Note: In this example, database connection object is assumed // to be created via other means (via life cycle event // mechanism) // and saved in ServletContext object. This is to share a same // database connection object among multiple servlets public void init() throws ServletException {
bookDB = (BookDB)getServletContext().getAttribute("bookDB");
if (bookDB == null) throw new UnavailableException("Couldn't get
database"); }...}
Example: destroy()public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {bookDB = (BookDB)getServletContext().
getAttribute("bookDB");if (bookDB == null)
throw new UnavailableException("Couldn't get database");
}
public void destroy() {bookDB = null;
}...}
service()• Is called in a new thread by server for each request• Dispatches to doGet, doPost, etc• service() methods take generic requests and responses:
service(ServletRequest request, ServletResponse response)
• Do not override
this method!
doGet, doPost, doXxx• Handles GET, POST and other requests
• Override these to provide desired behavior
Things to do in doGet() & doPost()• Extract client-sent information (HTTP parameter)
from HTTP request
• Set (save) and get (read) attributes to/from Scope objects
• Perform some business logic or access database
• Optionally forward the request to other Web components (Servlet or JSP)
• Populate HTTP response message and send it to client
Steps of Populating HTTP Response• Fill Response headers
• Set some properties of the response
• Buffer size
• Get an output stream object from the response
• Write body content to the output stream
Example: Simple Responsepublic class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
// Fill response headersresponse.setContentType("text/html");// Set buffer sizeresponse.setBufferSize(8192);// Get an output stream object from the responsePrintWriter out = response.getWriter();// Write body content to output streamout.println("<title>First Servlet</title>");out.println("<big>Hello J2EE Programmers!</big>")
}}
Scope Objects• Enables sharing information among
collaborating web components via attributes maintained in Scope objects• Attributes are name/object pairs
• Attributes maintained in the Scope objects are accessed with• getAttribute() & setAttribute()
• 4 Scope objects are defined• Web context, session, request, page
Four Scope Objects: Accessibility• Web context
• Accessible from Web components within a Web context
• Session• Accessible from Web components handling a request
that belongs to the session• Request
• Accessible from Web components handling the request
• Page• Accessible from JSP page that creates the object
Four Scope Objects: Classes• Web context
javax.servlet.ServletContext
• Sessionjavax.servlet.http.HttpSession
• Requestjavax.servlet.http.HttpServletRequest
• Pagejavax.servlet.jsp.PageContext
WebContext (ServletContext)• Used by servets to
• Set and get context-wide (application-wide) object-valued attributes
• Get request dispatcher• To forward to or include web component
• Access Web context-wide initialization parameters set in the web.xml file
• Access Web resources associated with the Web context
• Log• Access other misc information
Scope of ServletContext• There is one ServletContext object per
"web application" per Java Virtual Machine
How to Access ServletContext?• Within your servlet code, call
getServletContext()
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
// Get context-wide attribute value from
// ServletContext object
bookDB = (BookDB)getServletContext().
getAttribute("bookDB");
if (bookDB == null)
throw new UnavailableException(
"Couldn't get database");
}
Dispatching to Another Component
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");
// set headers and buffer size before accessing the Writer
response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>head><title>" + messages.getString("TitleBookDescription") + "</title></head></html>");
// Get the dispatcher; it gets the banner to the user
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
dispatcher.include(request, response);
...
Loggingpublic void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
getServletContext().log(“Life is good!”);
...
getServletContext().log(“Life is bad!”, someException);
Session Tracking• Why session tracking?
• User registration• Web page settings• On-line shopping cart
• HTTP is stateless!• Have to use specific methods:
• Cookies• Hidden Form Fields• URL Rewriting
Cookies• Idea: associate cookie with data on server
String sessionID = makeUniqueString();HashMap sessionInfo = new HashMap();HashMap globalTable = findTableStoringSessions();globalTable.put(sessionID, sessionInfo);Cookie sessionCookie =
new Cookie("JSESSIONID", sessionID);sessionCookie.setPath("/");response.addCookie(sessionCookie);
• Still to be done:• Extracting cookie that stores session identifier• Setting appropriate expiration time for cookie• Associating the hash tables with each request• Generating the unique session identifiers
Hidden Form Fields• Idea:
<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">
• Advantage• Works even if cookies are disabled or
unsupported
• Disadvantages• Lots of tedious processing• All pages must be the result of form
submissions
URL Rewriting• Idea
• Client appends some extra data on the end of each URL that identifies the session
• Server associates that identifier with data it has stored about that session
• E.g., http://host/path/file.html;jsessionid=1234
• Advantage• Works even if cookies are disabled or unsupported
• Disadvantages• Must encode all URLs that refer to your own site• All pages must be dynamically generated• Fails for bookmarks and links from other sites
The Session Tracking API• Session tracking API built on top of URL
rewriting or cookies• Look up HttpSession object associated with
current request (or create new one)• All cookie/URL rewriting mechanics hidden
• Look up information associated with a session
• Associate information with a session
Example: Looking Up Session
HttpSession session = request.getSession(true);ShoppingCart sc = (ShoppingCart)
session.getAttribute("shoppingCart");if (cart == null) {
cart = new ShoppingCart();session.setAttribute("shoppingCart", cart);
}...// do something with your shopping cart object
HttpSession Methods• getAttribute(String name)
• Extracts a previously stored value from a session object. Returns null if no value is associated with given name.
• setAttribute(name, value)• Associates a value with a name. Monitor changes: values implement
HttpSessionBindingListener.
• removeAttribute(name)• Removes values associated with name
• getAttributeNames()• Returns names of all attributes in the session
• getId()• Returns the unique identifier
HttpSession Methods• isNew()
• Determines if session is new to client (not to page)
• getCreationTime()• Returns time at which session was first created
• getLastAccessedTime()• Returns time at which session was last sent from client
• getMaxInactiveInterval, setMaxInactiveInterval• Gets or sets the amount of time session should go without
access before being invalidated
• invalidate()• Invalidates current session
Getting Request Parameters• A request can come with any number of parameters
• Parameters are sent from HTML forms:• GET: as a query string, appended to a URL• POST: as encoded POST data, not appeared in the URL
• getParameter("paramName”)• Returns the value of paramName• Returns null if no such parameter is present• Works identically for GET and POST requests
Getting Information From Response• Client information
• String request.getRemoteAddr()• String request.getRemoteHost()
• Server information• String request.getServerName()• int request.getServerPort()
• Misc• ServletInputStream getInputStream()• BufferedReader getReader()• String getProtocol()• String getContentType()• boolean isSecure()
Servlet 2.4 vs Servlet 2.5• A new dependency on J2SE 5.0 • Support for annotations
• @Resource, @PostConstruct and @PreDestroy, @EJB, @WebServiceRef, @DeclareRoles, @RunAs
• Several web.xml conveniences• Servlet name wildcarding• Multiple patterns in mappings
• A handful of removed restrictions • Error handling• Session tracking
• Some edge case clarifications
References• Java Servlet Specification 2.4
http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html
• J2EE Tutorial “Java Servlet Technology”
http://java.sun.com/javaee/5/docs/tutorial/doc/bnafd.html
• New features added to Servlet 2.5 http://www.javaworld.com/javaworld/jw-01-2006/jw-0102-servlet.html?page=3
• Servlet Basics presentationhttp://www.javapassion.com/j2ee/ServletBasics_speakernoted.pdf