Скачать презентацию Servlets Part 2 Modified slides from Dr Sagiv Скачать презентацию Servlets Part 2 Modified slides from Dr Sagiv

fe3bc6799b8d4e4c1f5ca228cfc9a035.ppt

  • Количество слайдов: 40

Servlets Part 2 Modified slides from Dr. Sagiv 1 Servlets Part 2 Modified slides from Dr. Sagiv 1

Servlets and Cookies Cookie Example 2 Servlets and Cookies Cookie Example 2

Servlets and Cookies • Java Servlet API provides comfortable mechanisms to handle cookies • Servlets and Cookies • Java Servlet API provides comfortable mechanisms to handle cookies • The class javax. servlet. http. Cookie represents a cookie - Getter methods: • get. Name(), get. Value(), get. Path(), get. Domain(), get. Max. Age(), get. Secure()… - Setter methods: • set. Value(), set. Path(), set. Domain(), set. Max. Age()… 3

Servlets and Cookies (cont( • Get the cookies from the service request: Cookie[] Http. Servlets and Cookies (cont( • Get the cookies from the service request: Cookie[] Http. Servlet. Request. get. Cookies() • Add a cookie to the service response: Http. Servlet. Response. add. Cookie(Cookie cookie) 4

An Example getname. html <html> <head><title>Insert your Name</title></head> <body> <h 1>What is your name? An Example getname. html Insert your Name What is your name?

5

An Example (cont( Welcome. Back. java public class Welcome. Back extends Http. Servlet { An Example (cont( Welcome. Back. java public class Welcome. Back extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { String user = req. get. Parameter("username"); if (user == null) { // Find the "username" cookie Cookie[] cookies = req. get. Cookies(); for (int i = 0; cookies != null && i < cookies. length; ++i) { if (cookies[i]. get. Name(). equals("username")) user = cookies[i]. get. Value(); } } else res. add. Cookie(new Cookie("username", user)); 6

An Example (cont( if (user == null) // No parameter and no cookie res. An Example (cont( if (user == null) // No parameter and no cookie res. send. Redirect("getname. html"); res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); out. println("Welcome Back " + user + ""); } } Welcome. Back. java 7

Session Management with Servlets 8 Session Management with Servlets 8

Session Cookies request id 1 Web browser 1 request Servlet put cookie id 1 Session Cookies request id 1 Web browser 1 request Servlet put cookie id 1 response Create Session Web server 9

Session Cookies request id 2 Web browser 2 request put cookie id 2 response Session Cookies request id 2 Web browser 2 request put cookie id 2 response Servlet id 2 id 1 response Create Session Web server 10

Session Cookies request Cookie: id 1 Web browser 1 Servlet id 2 response id Session Cookies request Cookie: id 1 Web browser 1 Servlet id 2 response id 1 Web server response Session read/write 11

Session Cookies request Cookie: id 2 Web browser 2 Servlet id 2 response id Session Cookies request Cookie: id 2 Web browser 2 Servlet id 2 response id 1 Web server response Session read/write 12

session. Id list 13 session. Id list 13

Accessing the Session Data • The session object is represented by the class Http. Accessing the Session Data • The session object is represented by the class Http. Session • Use the methods get. Sesssion() or get. Session(true) of the do. XXX request to get the current Http. Session object, or to create one if it doesn’t exist - When a new session is created, the server automatically add a session cookie to the response • Use get. Session(false) if you do not want to create a new session when no session exists 14

Http. Session Methods • Session data is accessed in a hash-table fashion: - set. Http. Session Methods • Session data is accessed in a hash-table fashion: - set. Attribute(String name, Object value) - Where is this value stored? - Object get. Attribute(String name) • More methods: - remove. Attribute, get. Attribute. Names - is. New, invalidate, get. Id - get. Creation. Time, get. Last. Accessed. Time - get. Max. Inactive. Interval, set. Max. Inactive. Interval 15

Example: A Basic Shopping Cart • In the following example a basic shopping cart Example: A Basic Shopping Cart • In the following example a basic shopping cart for an online store is implemented • The application consists of two Servlets: - Store. java: the main store site - Shopping. Cart. java: handles cart manipulation 16

Online-Store Example Store. java public class Store extends Http. Servlet { public void do. Online-Store Example Store. java public class Store extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); out. println("" + ""); Http. Session session = req. get. Session(); if (session. get. Attribute("item-list") == null) { out. println("Hello new visitor!"); session. set. Attribute("item-list", new Linked. List()); } 17 List item. List = (List) session. get. Attribute("item-list");

Your Shopping Cart:

    "); for (Iterator it =" src="https://present5.com/presentation/fe3bc6799b8d4e4c1f5ca228cfc9a035/image-18.jpg" alt="Online-Store Example (cont( out. println("Your Shopping Cart:
      "); for (Iterator it =" /> Online-Store Example (cont( out. println("Your Shopping Cart:
        "); for (Iterator it = item. List. iterator(); it. has. Next(); ) out. println("
      1. " + it. next() + "
      2. "); out. println("
      "); out. println("
      "); out. println("

      Add item: " + "

      " + "

      "); out. println(""); } } Store. java 18

Online-Store Example (cont( Shopping. Cart. java public class Shopping. Cart extends Http. Servlet { Online-Store Example (cont( Shopping. Cart. java public class Shopping. Cart extends Http. Servlet { public void do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { res. set. Content. Type("text/html"); Print. Writer out = res. get. Writer(); List items = (List) req. get. Session(). get. Attribute("item-list"); out. println("" + ""); 19

Online-Store Example (cont( if (req. get. Parameter( Online-Store Example (cont( if (req. get. Parameter("clear") != null) { items. clear(); out. println("Your Shopping Cart is Empty!"); } else { String item = req. get. Parameter("item"); items. add(item); out. println("The item " + item + " was added to your cart. "); } out. println("Return to the store"); out. println(""); }} Shopping. Cart. java 20

URL Rewriting request Servlet response Web browser id 1 response Create Session Web server URL Rewriting request Servlet response Web browser id 1 response Create Session Web server … … 21

Servlet URL Rewriting • Use the following methods of the do. XXX response object Servlet URL Rewriting • Use the following methods of the do. XXX response object to rewrite URLs: - String encode. URL(String url) • Use for HTML hyperlinks - String encode. Redirect. URL(String url) • Use for HTTP redirections • These methods contain the logic to determine whether the session ID needs to be encoded in the URL • For example, if the request has a cookie, then url is returned unchanged • Some servers implement the two methods identically 23

The Session Listener • The session listener reacts to the following events: - A The Session Listener • The session listener reacts to the following events: - A new session has been created - A session is being destroyed • To obtain a session listener, implement the interface javax. servlet. http. Http. Session. Listener 25

Session-Listener Example (cont( public class Cart. Initializer implements Http. Session. Listener { public void Session-Listener Example (cont( public class Cart. Initializer implements Http. Session. Listener { public void session. Created(Http. Session. Event se) { List item. List = new Linked. List(); se. get. Session(). set. Attribute("item-list", item. List); item. List. add("A Free Apple"); } public void session. Destroyed(Http. Session. Event se) {} } Cart. Initializer. java Cart. Initializer web. xml 26

The Servlet Context 27 The Servlet Context 27

Uses of Servlet. Context • For communicating with the Servlet container (e. g. , Uses of Servlet. Context • For communicating with the Servlet container (e. g. , Tomcat server), we use the Servlet. Context object • One context is shared among all Web-application Servlets • Can store Web application initialization parameters • Can store and manipulate application-shared attributes • Can be used to access the logger • Can be used to dispatch requests to other resources 28

Servlet. Context Methods • Access initialization parameters: get. Init. Parameter(String name), get. Init. Parameter. Servlet. Context Methods • Access initialization parameters: get. Init. Parameter(String name), get. Init. Parameter. Names() • Read Web-application attributes: get. Attribute(String name), get. Attribute. Names() • Manipulate Web-application attributes: set. Attribute(String, Object), remove. Attribute(String) • Transform context-relative paths to absolute paths: get. Real. Path(String path), URL get. Resource(String path) 29

Servlet. Context Methods • Write to the application log: log(String msg), log(String message, Throwable Servlet. Context Methods • Write to the application log: log(String msg), log(String message, Throwable exception) • Get a resource dispatcher (discussed later): Request. Dispatcher get. Request. Dispatcher(String path) • Name and version of the Servlet container: String get. Server. Info() 30

Note about Servlet. Context • There is a single Servlet. Context per Web application Note about Servlet. Context • There is a single Servlet. Context per Web application • Different Sevlets will get the same Servlet. Context object, when calling get. Servlet. Context during different sessions • You can lock the context to protect a critical section from all Web-application accesses 31

The Request Dispatcher 32 The Request Dispatcher 32

The Request Dispather • The Request. Dispatcher object is used to send a a The Request Dispather • The Request. Dispatcher object is used to send a a client request to any resource on the server • Such a resource may be dynamic (e. g. a Servlet or a JSP file) or static (e. g. a HTML document) • To send a request to a resource x, use: get. Servlet. Context(). get. Request. Dispatcher("x") 33

Request Dispatcher Methods • void forward(Servlet. Request request, Servlet. Response response) - Forwards a Request Dispatcher Methods • void forward(Servlet. Request request, Servlet. Response response) - Forwards a request from a Servlet to another resource • void include(Servlet. Request request, Servlet. Response response) - Includes the content of a resource in the response 34

Passing on Data • 3 different ways to pass parameters for the forwarded Servlet Passing on Data • 3 different ways to pass parameters for the forwarded Servlet or JSP - Data that will be used only for this request: request. set. Attribute("key", value); - Data will be used for this client (also for future requests): session. set. Attribute("key", value); - Data that will be used in the future for every client context. set. Attribute("key", value); 35

An Example • The Servlet Jokes. And. Images enables a user to choose a An Example • The Servlet Jokes. And. Images enables a user to choose a random joke or a random image • The server has 5 images in the directory images/ and five jokes (txt files) in the directory jokes/ • Empty requests are forwarded to a HTML file that enables the user to choose a joke or an image • Requests to a joke are forwarded to the servlet Jokes • Requests to an image are forwarded to a random image from the directory images/ 36

Jokes and Images <html> <head><title>Images and Jokes</title></head> <body> <h 1>Please Select: </h 1> <form Jokes and Images Images and Jokes Please Select: images. Jokes. Options. html 37

Jokes and Images (cont( public class Jokes. And. Images extends Http. Servlet { public Jokes and Images (cont( public class Jokes. And. Images extends Http. Servlet { public void do. Post(Http. Servlet. Request req, Http. Servlet. Response res) throws Servlet. Exception, IOException { int random. Num = 1 + Math. abs((new Random()). next. Int() % 5); if (req. get. Parameter("joke") != null) { req. set. Attribute("joke. Number", new Integer(random. Num)); get. Servlet. Context(). get. Request. Dispatcher("/Jokes"). forward(req, res); } else if (req. get. Parameter("image") != null) { get. Servlet. Context(). get. Request. Dispatcher("/images/image" + random. Num + ". gif"). forward(req, res); } else get. Servlet. Context(). get. Request. Dispatcher ("/images. Jokes. Options. html"). forward(req, res); } 38 public void do. Get. . . }} Jokes. And. Images. java

Forwarding versus Redirection • By default, Send. Redirect does not preserve parameters of the Forwarding versus Redirection • By default, Send. Redirect does not preserve parameters of the request • Send. Redirect ends up with a different URL on the client 40