servlet threads and sessions

23
CS-4220 Dr. Mark L. Hornick 1 Servlet Threads and Sessions

Upload: ocean

Post on 15-Feb-2016

18 views

Category:

Documents


0 download

DESCRIPTION

Servlet Threads and Sessions. Servlet execution. What are some ramifications of running each doGet () or doPost () on a separate thread??. What can happen here?. User 1 hits Submit on a form page. service(request, response). service(request, response). Thread 19. User 1. Data store. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Servlet  Threads and Sessions

CS-4220 Dr. Mark L. Hornick 1

Servlet Threads and Sessions

Page 2: Servlet  Threads and Sessions

CS-4220 Dr. Mark L. Hornick 2

Servlet execution

What are some ramifications of running each doGet() or doPost()on a separate thread??

Page 3: Servlet  Threads and Sessions

What can happen here?

CS-4220 Dr. Mark L. Hornick 3

User 1

User 1 hits Submit on a form page.

Thread 19

User 2

Thread 20 Data

store

User 2 hits Submit on the same form page at about the same time.

service(request, response)

service(request, response)

Assume the Datastore is managed via a Servlet-owned reference.

Page 4: Servlet  Threads and Sessions

Multithreading is a fact of a Servlet’s lifeThe only code objects that are thread-safe are

the ones that are stack-based (or readonly): HttpServletRequest object HttpServletResponse object Local Servlet method variables Servlet class/instance constants

These are NOT thread-safe: Servlet class attribute variables ServletConfig object ServletContext object

CS-4220 Dr. Mark L. Hornick 4

These first three are unique to eachthread.

Reading is thread-safe

These are objects are shared among threads.

Page 5: Servlet  Threads and Sessions

Are any of the following good approaches to avoid threading problems?1. Synchronize a Servlet’s service methods

Let only a single thread at a time execute doGet(), doPost(), etc

2. Synchronize a block of code within a method Let only a single thread at a time execute critical sections.

3. Synchronize on the ServletConfig object Let only a single thread at a time access any Servlet-specific

data

4. Synchronize on the ServletContext object Let only a single thread at a time access any Context-specific

(that is, web application-specific) data

CS-4220 Dr. Mark L. Hornick 5

Page 6: Servlet  Threads and Sessions

Another problem: If we use a Servlet’s attributes to store data, only that Servlet can access the data

CS-4220 Dr. Mark L. Hornick 6

Thread 19

Thread 20 Data

store

service(request, response)

service(request, response)

What if we wanted a different Servlet to generate the response, in order to separate class responsibilities and improve cohesion?

And what happens if our Servlet is used in another web app on the same server???

Page 7: Servlet  Threads and Sessions

Using ServletContext to store data would make it accessible to all Servlets in the web app.

CS-4220 Dr. Mark L. Hornick 7

Note: This diagram canbe found in your textbook

The ServletContext is initializedby Tomcat before any Servlet is initialized.

Page 8: Servlet  Threads and Sessions

We know we can use the DD to create ServletContext String parameters…

<?xml version="1.0" encoding="UTF-8"?>...<servlet>

<servlet-name>MyServlet</servlet-name><servlet-class>myPackage.MyServlet</servlet-class>

...</servlet><servlet>... Some other servlet’s defn goes here</servlet>...<!-- Here is a context parameter that all Servlets in this web app can see --> <context-param>

<param-name>lab1_version</param-name><param-value>2.1</param-value>

</context-param>

...</web-app>

CS-4220 Dr. Mark L. Hornick 8

But what if we want to initialize something more complex?

Page 9: Servlet  Threads and Sessions

ServletContext: Parameters vs. Attributes Parameters are init’d in the DD Parameters are name/value pairs,

where the value is a String Parameters are readonly

Attributes can be created/modified by code

Attributes are name/value pairs, where the value is an Object

Attributes are read/write

CS-4220 Dr. Mark L. Hornick 9

Page 10: Servlet  Threads and Sessions

We need a way to initialize a complex ServletContext attribute before any Servlets are initialized

Solution: Use a class that implements the ServletContextListener interface

CS-4220 Dr. Mark L. Hornick 10

This is one of 8 different Listeners

The event class

Page 11: Servlet  Threads and Sessions

The contextInitialized() event handler is called by Tomcat at startup

In the contextInitialized() method, we can create a ServletContext attribute that is a complex datatype:

public void contextInitialized(ServletContextEvent e) {ServletContext context = e.getServletContext();context.setAttribute(“foo”, new

MyComplexType() );}

// later, any Servlet will be able to access MyComplexType via a call to getServletContext().getAttribute(“foo”);

CS-4220 Dr. Mark L. Hornick 11

Page 12: Servlet  Threads and Sessions

We need to register ServletContextListeners with Tomcat in the DD:

<?xml version="1.0" encoding="UTF-8"?>...<servlet>

<servlet-name>MyServlet</servlet-name><servlet-class>test.HelloWorldServlet</servlet-class>

...</servlet><servlet>... Some other servlet’s defn goes here</servlet>...<!– Here’s how a ServletContextListener is registered --> <listener>

<listener-class>myPackage.MyContextListener</listener-class></listener...

</web-app>

CS-4220 Dr. Mark L. Hornick 12

Page 13: Servlet  Threads and Sessions

Finally…thread-safe data accessed as a ServletContext attribute

All users sharing the same object maintained by the ServletContext… Is this really what we want??

CS-4220 Dr. Mark L. Hornick 13

Page 14: Servlet  Threads and Sessions

By default, Servlets have no memory of who makes a request The HTTP protocol is stateless,

meaning it does not keep track of ongoing request/response messages.

Each HTTP request/response is independent of any other request/response

CS-4220 Dr. Mark L. Hornick 14

?

Page 15: Servlet  Threads and Sessions

CS-422Dr. Mark L. Hornick

15

Stateless Pro/ConGood for browsing and hyperlinking

pages in any order without regard to past history No HTTP overhead in maintaining state

Bad for applications that require complex user interaction between web pages The web application may want/need to

know what page you’ve visited previous to the current

page What you’ve done on previous visits

Page 16: Servlet  Threads and Sessions

A Cookie is a small amount of information that can be used to implement stateAs a web site developer, you can store

information you gather from a user on the file system of the user’s PC as a Cookie Previous date of web site access Login status . . .

CS-422Dr. Mark L. Hornick

16Web Browser Cookie information

Page 17: Servlet  Threads and Sessions

A Cookie has various properties

name – the cookie name value – the value of the cookie expires – the date the cookie expires path – path in domain in which cookie is visible domain – domain the cookie is visible to secure – cookie is only available over secure

connections httponly – cookie is only available via HTTP

CS-422Dr. Mark L. Hornick

17

Page 18: Servlet  Threads and Sessions

CS-422Dr. Mark L. Hornick

18

A web server can ask a browser to set/read/send Cookies as part of the HTTP header

Web BrowserWeb Server

HTTP request: “give me a page”

HTTP response: “OK, and BTW,store this Cookie”

Page 19: Servlet  Threads and Sessions

CS-422Dr. Mark L. Hornick

19

On subsequent visits, the web server can retrieve the Cookies via the HTTP header

Web BrowserWeb Server

HTTP request: “give me that page again”

HTTP response: “OK, give me thatCookie you stored last time so I cancustomize the page”

Page 20: Servlet  Threads and Sessions

CS-422Dr. Mark L. Hornick

20

Session Protocol User's browser is given a session ID by the server

Tomcat does this automatically Cookie expiration is usually very short; sometimes longer

ID is included in subsequent HTTP exchanges with the server “subsequent” can be even weeks later (usually not)

Server uses received session ID to locate/ retrieve corresponding session data/variables

Session variables kept on server for efficiency and security Persist somewhere on the server filesystem or server db

Page 21: Servlet  Threads and Sessions

Application Session lifetime can be adjusted

<?xml version="1.0" encoding="UTF-8"?>...<servlet>

<servlet-name>HelloWorld</servlet-name><servlet-class>test.HelloWorldServlet</servlet-class>

...</servlet><servlet>... Some other servlet’s defn goes here</servlet>...<!– Session life in minutes; 0 means end w/ browser session --> <session-config>

<session_timeout>30</session_timeout> </session-config>...

</web-app>

CS-4220 Dr. Mark L. Hornick 21

Page 22: Servlet  Threads and Sessions

Tomcat handles session management for Servlets

CS-4220 Dr. Mark L. Hornick 22

A reference to an HTTPServletRequest is created by the Containerand passed to the doGet() and doPost() methods of an HTTPServlet.

Session references are retrieved from the Request object.

Page 23: Servlet  Threads and Sessions

This is what we really want

CS-4220 Dr. Mark L. Hornick 23

User 1

User 1 hits Submit on a form page.

Thread 19

User 2

Thread 20

Datastore

User 2 hits Submit on the same form page at about the same time.

service(request, response)

service(request, response)

Each user gets a separate session object which can be used to manage separate data stores.

Datastore

User1 session

User2 session