Outline: Servlet Lifecycle Request and Response Session Management Javaserver Pages (JSP)
Outline: Servlet Lifecycle Request and Response Session Management Javaserver Pages (JSP)
HTTP Servlet Basics Servlet Lifecycle Request and Response Session Management JavaServer Pages (JSP)
Servlet API
javax.servlet
Support generic, protocol-independent servlets
Servlet (interface) GenericServlet (class)
service()
javax.servlet.http
Extended to add HTTP-specific functionality
HttpServlet (extends GenericServlet )
doGet() doPost()
User-defined Servlets
Inherit from HttpServlet Override doGet() and doPost()
To handle GET and POST requests
Hello World
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
End-to-end Process
Client
Makes a request to a servlet
Web Server
Receives the request Identifies the request as a servlet request Passes the request to the servlet container
Servlet Lifecycle
Servlet Container
Locates the servlet Passes the request to the servlet
Servlet
Executes in the current thread The servlet can store/retrieve objects from the container Output is sent back to the requesting browser via the web server Servlet continues to be available in the servlet container
9 10
Servlet Container
Provide web server with servlet support
Execute and manage servlets E.g., Tomcat
Loading Servlet
Server calls servlets init() method
After the server constructs the servlet instance and before the servlet handles any requests
init()
Servlet initialization is defined May be called
When the server starts When the servlet is first requested, just before the service() method is invoked At the request of the server administrator
11 12
Three types
Standalone container Add-on container Embeddable container
Removing Servlet
Server calls the destroy() method
After the servlet has been taken out of service and all pending requests to the servlet have completed or timed out
destroy()
Resources acquired should be freed up A chance to write out its unsaved cached info Last step before being garbage collected
A Simple Counter
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); } }
15 16
Multi-threading
Thread Safety
Non-local variables are not thread-safe
Variables declared within a class but outside any specific method May cause data corruption and inconsistencies
In the example
count ++ count ++ out.println out.println // thread 1 // thread 2 // thread 1 // thread 2
Each client request is another thread that calls the servlet via the service(), doGet(), and doPost() methods
17
Synchronization
Place code within a synchronization block
Guaranteed not to be executed concurrently by another thread
Option 2
PrintWriter out = res.getWriter(); synchronized(this) {
count++; out.println("Since loading, this servlet has been accessed " + count + " times.");
} out.println("Since loading, this servlet has been accessed " + count + " times.");
Option 4
Dont care; I can live with the inconsistency
20
HttpServletRequest
Encapsulate all information from the client request
https://glassfish.dev.java.net/nonav/javaee5/api/index.html
HttpServletResponse
Encapsulate all data to be returned to client
HTTP response header and response body (optional)
Convenience methods
setContentType(), sendRedirect(), sendError()
POST
Form parameters are included in the request body On reload
Browser will ask if it should re-post
Session Management
Provide state between HTTP requests
Client-side
Session Management
Server-side
Servlets built-in session tracking
25 26
Persistent Cookies
Stored at the browser
As name=value pairs Browsers limit the size of cookies Users can refuse to accept them
Cookie
Adding a Cookie
MaxAge
Given in seconds If negative, cookie persists until browser exists
Attached to subsequent requests to the same server Servlets can create cookies
Included in the HTTP response header
27
Cookie(String name, String value) setMaxAge(int expiry) setDomain(String pattern) setPath(String uri) setSecure(boolean flag)
Domain
Return cookie to servers matching the specified domain pattern By default, only return to the server that sent it
HttpServletResponse
addCoockie(Cookie cookie)
Path
Where the client should return the cookie Visible to all the pages in the specified directory and subdirectory
Secure flag
Send cookie only on secure channels
28
Retrieving Cookies
HttpServletRequest
public Cookie[] getCookies()
Cookie
getName() getValue() getDomain() getPath() getSecure()
29
Session Attributes
To add data to a session object
public void HttpSession.setAttribute(String name, Object value)
Session Lifecycle
Sessions do not last forever
Expire automatically due to inactivity
Default 30 min
void invalidate()
Invalidates this session then unbinds any objects bound to it
long getCreationTime()
Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT
long getLastAccessedTime()
Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request
33 34
ServletContext
Reference to the web application in which servlets execute
One ServletContext for each app on the server Allow servlets to access server information
ServletContext GenericServlet.getServletContex()
Configured individually
public void HttpSession.setMaxInactiveInterval(int secs) public int HttpSession.getMaxInactiveInterval()
Terminating a session
session.invalidate() Deletes session related attributes form server Removes cookie from client
JavaServer Pages
Embed Java servlet code in HTML pages Purposes
Enable the separation of dynamic and static content Enable the authoring of Web pages that create dynamic content easily but with maximum power and flexibility
request response
Java Compiler
Server automatically creates, compiles, loads, and runs a special servlet for the page
39
Servlet
40
Action tags
<jsp:include>
Occurs at request time; includes the output of the dynamic resource <jsp:include page=pathToDynamicResource flush=true/>
Directives
Control different aspects of the workhorse servlet <%@ directiveName attribName=attribValue %>
<%@ page contentType=text/plain %>
41
Forward a request
Occurs at request time <jsp:forward page=pathToDynamicResource />
42