SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Navaneethan Naveen
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT ExploitationAkshaeyBhosale
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Mediacurrent
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Introduction to xml
Introduction to xmlIntroduction to xml
Introduction to xmlGtu Booker
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 

Was ist angesagt? (20)

Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014
 
Json Web Token - JWT
Json Web Token - JWTJson Web Token - JWT
Json Web Token - JWT
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
JSON Web Token
JSON Web TokenJSON Web Token
JSON Web Token
 
Java servlets
Java servletsJava servlets
Java servlets
 
Html5-Web-Storage
Html5-Web-StorageHtml5-Web-Storage
Html5-Web-Storage
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Json web token
Json web tokenJson web token
Json web token
 
Introduction to xml
Introduction to xmlIntroduction to xml
Introduction to xml
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Servlets
ServletsServlets
Servlets
 

Ähnlich wie Lecture 3: Servlets - Session Management

Ähnlich wie Lecture 3: Servlets - Session Management (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlets
ServletsServlets
Servlets
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
struts
strutsstruts
struts
 
Servlet
ServletServlet
Servlet
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
 
SERVIET
SERVIETSERVIET
SERVIET
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NET
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Advance java session 19
Advance java session 19Advance java session 19
Advance java session 19
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
Servlet
ServletServlet
Servlet
 

Mehr von Fahad Golra

Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage CFahad Golra
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Fahad Golra
 
Seance 2 - Programmation en langage C
Seance 2 - Programmation en langage CSeance 2 - Programmation en langage C
Seance 2 - Programmation en langage CFahad Golra
 
Seance 1 - Programmation en langage C
Seance 1 - Programmation en langage CSeance 1 - Programmation en langage C
Seance 1 - Programmation en langage CFahad Golra
 
Tutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyTutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyFahad Golra
 
Tutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyTutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyFahad Golra
 
Tutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyTutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyFahad Golra
 
Tutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyTutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyFahad Golra
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Fahad Golra
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Fahad Golra
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)Fahad Golra
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RSFahad Golra
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, mavenFahad Golra
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEEFahad Golra
 
Deviation Detection in Process Enactment
Deviation Detection in Process EnactmentDeviation Detection in Process Enactment
Deviation Detection in Process EnactmentFahad Golra
 
Meta l metacase tools & possibilities
Meta l metacase tools & possibilitiesMeta l metacase tools & possibilities
Meta l metacase tools & possibilitiesFahad Golra
 

Mehr von Fahad Golra (18)

Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage C
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C
 
Seance 2 - Programmation en langage C
Seance 2 - Programmation en langage CSeance 2 - Programmation en langage C
Seance 2 - Programmation en langage C
 
Seance 1 - Programmation en langage C
Seance 1 - Programmation en langage CSeance 1 - Programmation en langage C
Seance 1 - Programmation en langage C
 
Tutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyTutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital Photography
 
Tutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyTutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital Photography
 
Tutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyTutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital Photography
 
Tutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyTutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital Photography
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEE
 
Deviation Detection in Process Enactment
Deviation Detection in Process EnactmentDeviation Detection in Process Enactment
Deviation Detection in Process Enactment
 
Meta l metacase tools & possibilities
Meta l metacase tools & possibilitiesMeta l metacase tools & possibilities
Meta l metacase tools & possibilities
 

Kürzlich hochgeladen

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Kürzlich hochgeladen (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Lecture 3: Servlets - Session Management

  • 1. JEE - Servlets Session 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 - 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
  • 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 • 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
  • 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 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
  • 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 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
  • 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 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
  • 15. 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
  • 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 • 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
  • 19. 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
  • 20. 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
  • 21. Context attributes • Across entire application • Shared across multiple servlets and users • Initialization code 21 Servlets Session Management
  • 22. 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
  • 23. 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
  • 24. Example - Servlet Attributes 24 First Browser Second Browser
  • 25. 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
  • 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 • 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
  • 30. 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
  • 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. 33 Servlets Session Management