JEE - Servlets Session
Management
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
Lecture 2 - Servlets Session
Management
• Servlet Filters
• Servlet Context & Config
• Session object
• Session API
• Session attributes
• Session Tracking
2 JEE - Servlets
Servlets - Writing Filters
• They are used to
• intercept requests from a client before they reach a servlet
• manipulate responses from server before they are sent to the
client
!
• Types of filters:
• Authentication
• Data compression
• Encryption
• Image conversion
• Logging & auditing
• XSL/T Filters to transform XML content, etc.
3 Servlets Session Management
Filters in Web.xml
• Deployed in web.xml where they map to servlet URL
patterns
!
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>com.ece.jee.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4 Servlets Session Management
Servlet Filters
• An instance of each filter declared in the deployment
descriptor is created when the web container starts.
!
• Filters execute in the order that they are declared in
the deployment descriptor.
!
• Methods to implement
• doFilter() - called each time a request/response is passed
through the chain
• init() - initializing and placing the filter in service
• destroy() - taking the filter out of service
5 Servlets Session Management
Filter Example
@WebFilter(description = "basic logging", urlPatterns = { "/*" })	
public class LogFilter implements Filter {	
!
	 public void init(FilterConfig fConfig) throws ServletException {	
	 	 // Called when filter is placed in service	
	 }	
!
	 public void destroy() {	
	 	 // Called when filter is removed from service	
	 }	
!
	 public void doFilter(ServletRequest request, ServletResponse response,	
	 	 	 FilterChain chain) throws IOException, ServletException {	
	 	 // Get the IP address of client machine.	
	 	 String ipAddress = request.getRemoteAddr();	
!
	 	 // Log the IP address and current timestamp.	
	 	 System.out.println("IP " + ipAddress + ", Time "	
	 	 	 	 + new Date().toString());	
!
	 	 // pass the request along the filter chain	
	 	 chain.doFilter(request, response);	
	 }	
}
6
Web Container - Servlet Context & Config
7 Servlets Session Management
web archive (war)
Servlet Context
Servlet 1 Servlet 2 Servlet 3 JSP 1
Servlet
Config
Servlet
Config
Servlet
Config
Servlet
Config
Initialization Parameters
8 Servlets Session Management
Context Init
Parameters
Servlet Init
Parameters
Scope
Scope is Web
Container
Specific to Servlet
or JSP
Servlet
code
getServletContext() getServletConfig()
Deployment
Descriptor
Within the <web-app>
element but not
within a specific
<servlet> element
Within the <servlet>
element for each
specific servlet
Servlet Init parameter - web.xml
<servlet>
<servlet-name>simpleServlet</servlet-name>
<servlet-class>com.ece.jee.SimpleServlet</servlet-class>
<init-param>
<param-name>myParam</param-name>
<param-value>paramValue</param-value>
</init-param>
</servlet>
9 Servlets Session Management
Init parameter - Servlet
public class SimpleServlet extends GenericServlet {
!
protected String myParam = null;
!
public void init(ServletConfig servletConfig) throws ServletException{
this.myParam = servletConfig.getInitParameter("myParam");
}
!
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.getWriter().write("<html><body>myParam = " +
this.myParam + "</body></html>");
}
}
10 Servlets Session Management
Load-on-startup
• By setting a <load-on-startup> element, you can tell the
servlet container to load the servlet as soon as the servlet
container starts
!
<servlet>
<servlet-name>controlServlet</servlet-name>
<servlet-class>com.ece.jee.SimpleServlet</servlet-class>
<init-param><param-name>container.script.static</param-name>
<param-value>/WEB-INF/container.script</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
11 Servlets Session Management
Context Init parameters
• Web.xml
!
<context-param>
<param-name>myParam</param-name>
<param-value>the value</param-value>
</context-param>
!
• Inside HTTPServlet subclass
!
String myContextParam =
request.getSession().getServletContext().getInitParameter("myParam");
12 Servlets Session Management
Request Object
• HTTP - Stateless Protocol
!
• How to make our web app remember us?
• Used for login screens, shopping carts etc.
!
• How to share values between different Servlets?
• How to share values between different users?
13 Servlets Session Management
Session
• Server will create session object
• assign unique ID
• track sessions by some method such as cookies or
URL rewriting
!
• Servlet can store anything in session context using
session attributes
!
• Getting the session object
HTTPSession session = req.getSession(true);
14 Servlets Session Management
Session API
• Getting the ID
String getId();
!
• Getting the creation date
long getCreationTime();
!
• Getting last access time
long getLastAccessTime();
!
• Terminating a session
void invalidate();
15 Servlets Session Management
Session API - Timeout
• Get the maximum inactive time (seconds) . After this
the session closes automatically.
!
int getMAxInactiveInterval();
!
!
• Setting the maximum inactive time. A negative value
means infinite time.
!
void setMaxInactiveInterval(int seconds);
16 Servlets Session Management
Web container - attributes
17 Servlets Session Management
Attributes Parameters
Types Context
Request
Session
Context Init
Request
Servlet Init
Method to set setAttribute(String,
Object)
We cannot set Init
parameters.
Return type Object String
Method to get getAttribute(String) getInitParameter
(String)
Request Attributes
• One per request
• Not available across multiple requests
• When you get redirected to another servlet, your request
dies
• Normally used for passing data from jsp to your
servlet when you submit the form.
18 Servlets Session Management
Session Attributes
• One per user/machine
• Object available across multiple requests
• Every request object has a handle to the session
object
• Used for
• Storing user credentials once user is authenticated.
• Checking if the user has right access to do operations like add/
delete/edit on some database.
• Once the session goes idle for x amount minutes, the
session dies and all info in it will be gone
19 Servlets Session Management
Session Attributes
• Placing attributes in session
session.setAttribute(“age”, “25”);
!
• Getting an attribute
Integer value = (Integer) session.getAttribute(“age”);
!
• Getting all attribute names
Enumeration aNames = request.getAttributeNames();
!
• Deleting an attribute
session.removeAttribute(“age”);
20 Servlets Session Management
Context attributes
• Across entire application
• Shared across multiple servlets and users
• Initialization code
21 Servlets Session Management
Example - Servlet Attributes
@WebServlet(description = "testing the session", urlPatterns = { "/
SessionServlet" })	
public class SessionServlet extends HttpServlet {	
	 private static final long serialVersionUID = 1L;	
!
	 protected void doGet(HttpServletRequest request,	
	 	 	 HttpServletResponse response) throws ServletException,
IOException {	
	 	 // Part 1: Get the Session & Context object	
	 	 HttpSession session = request.getSession(true);	
	 	 ServletContext context = request.getServletContext();	
!
	 	 // Part 2: Get the session data value	
	 	 Integer ival = (Integer) session.getAttribute("counter");	
	 	 if (ival == null)	
	 	 	 ival = new Integer(1);	
	 	 else	
	 	 	 ival = new Integer(ival.intValue() + 1);	
	 	 session.setAttribute("counter", ival);
22
Example - Servlet Attributes
	 	 // Part 3: Set the SessionContext attribute	
	 	 context.setAttribute("counterName", "Funny Counter");	
	 	 String name = (String) context.getAttribute("counterName");	
!
	 	 // Part 4: Output the page	
	 	 response.setContentType("text/html");	
	 	 PrintWriter out = response.getWriter();	
	 	 out.println("<html>");	
	 	 out.println("<head><title>Session Tracking Test</title></
head>");	
	 	 out.println("<body>");	
	 	 out.println("<h1>Session Tracking Test</h1>");	
	 	 out.println("You have hit this page " + ival + " times");	
	 	 out.println("You are using " + name);	
	 	 out.println("</body></html>");	
	 }	
}
23
Example - Servlet Attributes
24
First
Browser
Second
Browser
Session tracking
25 Servlets Session Management
client A Container
HttpSession
!
ID# 09AZ1
“User1”
request, “Serv A” new session
setAttribute(“user1”)
response, ID# 09AZ1
client A Container
HttpSession
!
ID# 09AZ1
“User1”
request, “Serv B”, ID# 09AZ1 search session ID# 09AZ1
getAttribute(“user1”)
response, “user1”, ID# 09AZ1
First Request
Subsequent Request
Session tracking - cookies
26 Servlets Session Management
client A Container
Http Response
!
HTTP/1.1 200 OK
Location: http://www.abcd.com/login
Set-Cookie: JSESSIONID=09AZ1
Domain=.abcd.com;path=/;HttpOnly
……
client A Container
Http Request
!
POST/login.do HTTP/1.1
Host: www.abcd.com
Cookie: JSESSIONID=09AZ1
……
First Response
Subsequent Requests
Session tracking - URL Rewriting
27 Servlets Session Management
client A Container
Http Response
!
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Location:
http://www.abcd.com/Login;JSESSIONID=09AZ1
client A Container
Http Request
!
GET /login;JSESSIONID=09AZ1
HTTP/1.1
Host:www.abcd.com
……
First Response
Subsequent Requests
Session tracking - URL Rewriting
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
…
!
// Get the current session ID
String sessionid = req.getPathInfo();
…..
out.println("<FORM ACTION="/servlet/ShoppingCart/" + sessionid +
"" METHOD=POST>”);
…..
}
28 Servlets Session Management
Session Tracking
• With first response server sends both cookies and url
rewriting.
!
• If the cookies are not blocked by the client, the server
chooses this method and manages the session
through cookies
!
• Incase cookies are disabled, then the clients next
request uses url rewriting. After this, server choosing
the url rewriting for maintaining the session.
29 Servlets Session Management
Problems with browser cache
• For the practical exercise on Login Servlets, the web
browsers may show you older pages and images,
store in cache.
!
• To avoid this, you can avoid cache in HTTP response
!
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
30 Servlets Session Management
Transferring Control - Forward
• Performed by servlet internally
• client browser does not know about it
• the client browser displays original request URL
!
• Browser Reload: means repeating the original request
!
• In the implementing method
!
RequestDispatcher rd = 	
	 request.getRequestDispatcher("SuccessServlet");	
rd.forward(request, response);
31
Transfering Control - Redirect
• Browser tells user web-browser to fetch a different
URL
• The browser request is a second request not the the
original request
• Slower than Forward
• Objects of original request are not available in the
second request
• Reload means a second request not repeating original
• In doPost or DoGet method
response.sendRedirect("SecondServlet");
32
33 Servlets Session Management

Lecture 3: Servlets - Session Management

  • 1.
    JEE - ServletsSession Management Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2.
    Lecture 2 -Servlets Session Management • Servlet Filters • Servlet Context & Config • Session object • Session API • Session attributes • Session Tracking 2 JEE - Servlets
  • 3.
    Servlets - WritingFilters • They are used to • intercept requests from a client before they reach a servlet • manipulate responses from server before they are sent to the client ! • Types of filters: • Authentication • Data compression • Encryption • Image conversion • Logging & auditing • XSL/T Filters to transform XML content, etc. 3 Servlets Session Management
  • 4.
    Filters in Web.xml •Deployed in web.xml where they map to servlet URL patterns ! <filter> <filter-name>LogFilter</filter-name> <filter-class>com.ece.jee.LogFilter</filter-class> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 4 Servlets Session Management
  • 5.
    Servlet Filters • Aninstance of each filter declared in the deployment descriptor is created when the web container starts. ! • Filters execute in the order that they are declared in the deployment descriptor. ! • Methods to implement • doFilter() - called each time a request/response is passed through the chain • init() - initializing and placing the filter in service • destroy() - taking the filter out of service 5 Servlets Session Management
  • 6.
    Filter Example @WebFilter(description ="basic logging", urlPatterns = { "/*" }) public class LogFilter implements Filter { ! public void init(FilterConfig fConfig) throws ServletException { // Called when filter is placed in service } ! public void destroy() { // Called when filter is removed from service } ! public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); ! // Log the IP address and current timestamp. System.out.println("IP " + ipAddress + ", Time " + new Date().toString()); ! // pass the request along the filter chain chain.doFilter(request, response); } } 6
  • 7.
    Web Container -Servlet Context & Config 7 Servlets Session Management web archive (war) Servlet Context Servlet 1 Servlet 2 Servlet 3 JSP 1 Servlet Config Servlet Config Servlet Config Servlet Config
  • 8.
    Initialization Parameters 8 ServletsSession Management Context Init Parameters Servlet Init Parameters Scope Scope is Web Container Specific to Servlet or JSP Servlet code getServletContext() getServletConfig() Deployment Descriptor Within the <web-app> element but not within a specific <servlet> element Within the <servlet> element for each specific servlet
  • 9.
    Servlet Init parameter- web.xml <servlet> <servlet-name>simpleServlet</servlet-name> <servlet-class>com.ece.jee.SimpleServlet</servlet-class> <init-param> <param-name>myParam</param-name> <param-value>paramValue</param-value> </init-param> </servlet> 9 Servlets Session Management
  • 10.
    Init parameter -Servlet public class SimpleServlet extends GenericServlet { ! protected String myParam = null; ! public void init(ServletConfig servletConfig) throws ServletException{ this.myParam = servletConfig.getInitParameter("myParam"); } ! public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.getWriter().write("<html><body>myParam = " + this.myParam + "</body></html>"); } } 10 Servlets Session Management
  • 11.
    Load-on-startup • By settinga <load-on-startup> element, you can tell the servlet container to load the servlet as soon as the servlet container starts ! <servlet> <servlet-name>controlServlet</servlet-name> <servlet-class>com.ece.jee.SimpleServlet</servlet-class> <init-param><param-name>container.script.static</param-name> <param-value>/WEB-INF/container.script</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> 11 Servlets Session Management
  • 12.
    Context Init parameters •Web.xml ! <context-param> <param-name>myParam</param-name> <param-value>the value</param-value> </context-param> ! • Inside HTTPServlet subclass ! String myContextParam = request.getSession().getServletContext().getInitParameter("myParam"); 12 Servlets Session Management
  • 13.
    Request Object • HTTP- Stateless Protocol ! • How to make our web app remember us? • Used for login screens, shopping carts etc. ! • How to share values between different Servlets? • How to share values between different users? 13 Servlets Session Management
  • 14.
    Session • Server willcreate session object • assign unique ID • track sessions by some method such as cookies or URL rewriting ! • Servlet can store anything in session context using session attributes ! • Getting the session object HTTPSession session = req.getSession(true); 14 Servlets Session Management
  • 15.
    Session API • Gettingthe ID String getId(); ! • Getting the creation date long getCreationTime(); ! • Getting last access time long getLastAccessTime(); ! • Terminating a session void invalidate(); 15 Servlets Session Management
  • 16.
    Session API -Timeout • Get the maximum inactive time (seconds) . After this the session closes automatically. ! int getMAxInactiveInterval(); ! ! • Setting the maximum inactive time. A negative value means infinite time. ! void setMaxInactiveInterval(int seconds); 16 Servlets Session Management
  • 17.
    Web container -attributes 17 Servlets Session Management Attributes Parameters Types Context Request Session Context Init Request Servlet Init Method to set setAttribute(String, Object) We cannot set Init parameters. Return type Object String Method to get getAttribute(String) getInitParameter (String)
  • 18.
    Request Attributes • Oneper request • Not available across multiple requests • When you get redirected to another servlet, your request dies • Normally used for passing data from jsp to your servlet when you submit the form. 18 Servlets Session Management
  • 19.
    Session Attributes • Oneper user/machine • Object available across multiple requests • Every request object has a handle to the session object • Used for • Storing user credentials once user is authenticated. • Checking if the user has right access to do operations like add/ delete/edit on some database. • Once the session goes idle for x amount minutes, the session dies and all info in it will be gone 19 Servlets Session Management
  • 20.
    Session Attributes • Placingattributes in session session.setAttribute(“age”, “25”); ! • Getting an attribute Integer value = (Integer) session.getAttribute(“age”); ! • Getting all attribute names Enumeration aNames = request.getAttributeNames(); ! • Deleting an attribute session.removeAttribute(“age”); 20 Servlets Session Management
  • 21.
    Context attributes • Acrossentire application • Shared across multiple servlets and users • Initialization code 21 Servlets Session Management
  • 22.
    Example - ServletAttributes @WebServlet(description = "testing the session", urlPatterns = { "/ SessionServlet" }) public class SessionServlet extends HttpServlet { private static final long serialVersionUID = 1L; ! protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Part 1: Get the Session & Context object HttpSession session = request.getSession(true); ServletContext context = request.getServletContext(); ! // Part 2: Get the session data value Integer ival = (Integer) session.getAttribute("counter"); if (ival == null) ival = new Integer(1); else ival = new Integer(ival.intValue() + 1); session.setAttribute("counter", ival); 22
  • 23.
    Example - ServletAttributes // Part 3: Set the SessionContext attribute context.setAttribute("counterName", "Funny Counter"); String name = (String) context.getAttribute("counterName"); ! // Part 4: Output the page response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Session Tracking Test</title></ head>"); out.println("<body>"); out.println("<h1>Session Tracking Test</h1>"); out.println("You have hit this page " + ival + " times"); out.println("You are using " + name); out.println("</body></html>"); } } 23
  • 24.
    Example - ServletAttributes 24 First Browser Second Browser
  • 25.
    Session tracking 25 ServletsSession Management client A Container HttpSession ! ID# 09AZ1 “User1” request, “Serv A” new session setAttribute(“user1”) response, ID# 09AZ1 client A Container HttpSession ! ID# 09AZ1 “User1” request, “Serv B”, ID# 09AZ1 search session ID# 09AZ1 getAttribute(“user1”) response, “user1”, ID# 09AZ1 First Request Subsequent Request
  • 26.
    Session tracking -cookies 26 Servlets Session Management client A Container Http Response ! HTTP/1.1 200 OK Location: http://www.abcd.com/login Set-Cookie: JSESSIONID=09AZ1 Domain=.abcd.com;path=/;HttpOnly …… client A Container Http Request ! POST/login.do HTTP/1.1 Host: www.abcd.com Cookie: JSESSIONID=09AZ1 …… First Response Subsequent Requests
  • 27.
    Session tracking -URL Rewriting 27 Servlets Session Management client A Container Http Response ! HTTP/1.1 200 OK Content-Type: text/html;charset=UTF-8 Location: http://www.abcd.com/Login;JSESSIONID=09AZ1 client A Container Http Request ! GET /login;JSESSIONID=09AZ1 HTTP/1.1 Host:www.abcd.com …… First Response Subsequent Requests
  • 28.
    Session tracking -URL Rewriting public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { … ! // Get the current session ID String sessionid = req.getPathInfo(); ….. out.println("<FORM ACTION="/servlet/ShoppingCart/" + sessionid + "" METHOD=POST>”); ….. } 28 Servlets Session Management
  • 29.
    Session Tracking • Withfirst response server sends both cookies and url rewriting. ! • If the cookies are not blocked by the client, the server chooses this method and manages the session through cookies ! • Incase cookies are disabled, then the clients next request uses url rewriting. After this, server choosing the url rewriting for maintaining the session. 29 Servlets Session Management
  • 30.
    Problems with browsercache • For the practical exercise on Login Servlets, the web browsers may show you older pages and images, store in cache. ! • To avoid this, you can avoid cache in HTTP response ! response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); 30 Servlets Session Management
  • 31.
    Transferring Control -Forward • Performed by servlet internally • client browser does not know about it • the client browser displays original request URL ! • Browser Reload: means repeating the original request ! • In the implementing method ! RequestDispatcher rd = request.getRequestDispatcher("SuccessServlet"); rd.forward(request, response); 31
  • 32.
    Transfering Control -Redirect • Browser tells user web-browser to fetch a different URL • The browser request is a second request not the the original request • Slower than Forward • Objects of original request are not available in the second request • Reload means a second request not repeating original • In doPost or DoGet method response.sendRedirect("SecondServlet"); 32
  • 33.