SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Secure Session Management
Secure Session ManagementSecure Session Management
Secure Session Management
 
Express js
Express jsExpress js
Express js
 
Servlets
ServletsServlets
Servlets
 
Spring boot
Spring bootSpring boot
Spring boot
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Json web token
Json web tokenJson web token
Json web token
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

Similaire à Lecture 3: Servlets - Session Management (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
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
 

Plus de 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
 

Plus de 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
 

Dernier

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
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
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Dernier (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
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"
 
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
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

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