Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Servlets – Part 2 Representation and Management of Data on the Web.

Similar presentations


Presentation on theme: "1 Servlets – Part 2 Representation and Management of Data on the Web."— Presentation transcript:

1 1 Servlets – Part 2 Representation and Management of Data on the Web

2 2 Announcement I have put an excellent book on Servlets and JSP pages at: –~dbi/Core-Servlets-and-JSP.pdf

3 3 What are Cookies used For? Identifying a user during an e-commerce (or other) session Avoiding user-name and password Customizing a site Focusing advertising

4 4 Cookies Cookies are state information that gets passed back and forth between the web server and browser in HTTP headers Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure A response header Cookie: NAME=VALUE; NAME2=VALUE2; NAME3=VALUE3... A request header

5 5 Problems A privacy threat: –search engine can remember previous searches –The computer that stores the cookie can allow an access to a site for a person that is not the person that the site recognizes However, cookies do not pose a security threat

6 6 Sharing Information Can two sites share the information that they have with cookies? What if the two sites use images from the same source?

7 7 javax.servlet.http.Cookie Cookies are represented with the class Cookie in javax.servlet.http A cookie object can be created by the cookie constructor The name and the value of the constructor should not include: []() =, “ / ? @ : ;

8 8 Cookies You create cookies and then add them to the HttpServletResponse –public Cookie[] getCookies() You can get cookies from the HttpServletRequest –public void addCookie(Cookie)

9 9 Properties of Cookies getDomain / setDomain –The domain for which the cookie belongs getMaxAge / setMaxAge –How long (in seconds) will the cookie last –Negative value = per-session cookie –Default: Only exists during session getName –The name of the cookie to identify it

10 10 Properties of Cookies getPath / setPath –Defines the path for which the cookie relates –Cookie.setPath(“/”) means that all the pages on host will get the cookie –Defualt: Entire host getSecure / setSecure –Should the cookie be sent with SSL secured line getValue / setValue –The value that the cookie holds*

11 11 Login Page Logon to My Site Your Name: HTML Page

12 12 import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class WelcomeBack extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("username"); if (user == null) { Cookie[] cookies = req.getCookies(); for (int i = 0 ; i < cookies.length ; i++) { if (cookies[i].getName().equals("username")) user = cookies[i].getValue(); } } else res.addCookie(new Cookie("username", user)); if (user != null) { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Welcome Back" + user + " "); } else { res.sendRedirect("/dbi/login.html"); } } }

13 13 Session Tracking HTTP is a stateless protocol Many web applications (i.e. shopping carts) are not stateless) Need to keep track of each user’s state (i.e. items in the shopping cart) Sessions can be managed using: cookies, hidden form fields or URL rewriting

14 14 Using Cookies: Intuition sessionIdsessionData dsf39324 324jlsdf 234jksdf 789388dd …… …… …… …… …… …… …… …… …… …… …… ……

15 15 Hidden Form Fields: Inutiton Hidden fields are just another type of input tag for a form The receiving web server can’t tell the difference between a user entered value and a hidden form field value For this to work: All pages must be results of form submission <INPUT TYPE = hidden NAME = “session” VALUE = “…” >

16 16 URL Encoding Client appends some extra data to all URLs of the session: –http://host/path/file.html?sessionid=455hh You must embed all links into your site! If you want to embed a link in a response, and want the link to reflect the session-id, use either (from HttpServletResponse) –public String encodeURL(String url) –public String encodeRedirectURL(String url) These encode the session id as ?name=value on the end of the url

17 17 Tracking with HttpSession Servlets have built-in session tracking Every user has a HttpSession object to store and retrieve user information, e.g., –shopping cart contents, –database connections Can be implemented using cookies/URL Encoding (for us it doesn’t make a difference which)

18 18 Getting the Session Retrieve the user’s session: (from the request object) HttpSession getSession(boolean create) if the user has no valid session, –a new one is created if create is true; –null is returned if create is false HttpSession's method isNew() returns true if the session is new to the client

19 19 Session Tracking API Add data to a session using HTTPSession's method: void setAttribute(String name, Object val) –value must implement Serializable interface –replaces any object that is bound in the session and has the same name Retrieve data from a session public Object getAttribute(String name) –returns null if no object is bound to the name

20 20 More on Tracking API Retrieve the name of all session objects –public Enumeration getAttributeNames() Remove an attribute from the session –public void removeAttribute(String name) –does nothing if no object is bound You can get the identifier of the object by –public String getId(String name) These methods throw an IllegalStateException if the session is invalid

21 21 import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class HitCount extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); HttpSession session = req.getSession(true); Integer count = (Integer)session.getValue("tracker.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.putValue("tracker.count", count); out.println(" You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.") + " "); }

22 22 Note about HTTPSession There is a single session per user, per session. Different Sevlets will get the same HttpSession object, when calling getSession on different HTTPServletRequest objects during the same session

23 23 ServletContext For sharing resources among servlets in the same web application, we use ServletContext Can store web application initialization parameters (similar to ServletConfig) Can store attributes (defined during lifetime of application) Access to logger Dispatching requests to other Servlets

24 24 ServletContext Methods Get a ServlerContext using getServletContext(). This is a method of Servlet Partial Method List: –public void log(String msg) –public void log(String msg, Throwable exception) –public String getRealPath(String path) –public Object getAttribute(String name) –public void setAttribute(String name, Object object) –public void removeAttribute(String name) –public RequestDispatcher getRequestDistpatcher(String Name);

25 25 Note about ServletContext There is a single ServletContext per web application Different Sevlets will get the same ServletContext object, when calling getServletContext during different sessions

26 26 Request Dispatcher Methods void forward (ServletRequest request, ServletResponse response) –Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server void include (ServletRequest request, ServletResponse response) –Includes the content of a resource (servlet, JSP page, HTML file) in the response

27 27 Passing on Data 3 different ways to set parameters for the forwarded servlet or JSP to see –Data that will be used only for this request: request.setAttribute("key", value); –Data will be used for this client (also for future requests): session.setAttribute("key", value); –Data that will be used in the future for any client context.setAttribute("key", value);

28 28 Fowarding Request Example Consider an online Travel Agent, as shown here here The Travel Servlet is called by the page The Travel Servlet sets some variables The request is then forwarded depending on the button that the user had pressed

29 29 public class Travel extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String emailAddress = request.getParameter("emailAddress"); String password = request.getParameter("password"); TravelCustomer customer = TravelCustomer.findCustomer(password, emailAddress); if (customer == null) gotoPage("/travel/Accounts", request, response); customer.setStartDate(request.getParameter("startDate")); customer.setEndDate(request.getParameter("endDate")); customer.setOrigin(request.getParameter("origin")); customer.setDestination(request.getParameter ("destination")); HttpSession session = request.getSession(true); session.putValue("customer", customer);

30 30 if (request.getParameter("flights") != null) { gotoPage("/travel/BookFlights", request, response); } else if (request.getParameter("cars") != null) { gotoPage("/travel/RentCars", request, response); } else if (request.getParameter("hotels") != null) { gotoPage("/travel/FindHotels", request, response); } else if (request.getParameter("cars") != null) { gotoPage("/travel/EditAccounts", request, response); } else gotoPage("/travel/IllegalRequest", request, response); } private void gotoPage(String address, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address); dispatcher.forward(request, response); }

31 31 Forward versus SendRedirect SendRedirect requires extra communication on part of the client: Why? SendRedirect does not have to preserve all the variables in the request SendRedirect ends up with a different URL on the client. What problems does this imply might happen when using Forward?

32 32 Include Forwarding a request completely services a request To include the result of a resource (html page, jsp page, servlet) in our response use the include method of RequestDispatcher

33 33 Servlet Chaining Servlets cooperate to create content Multiple servlets in a chain –request parameters supplied to first servlet –output from each Servlet piped to the next Servlet in the chain –last servlet in chain sends output to client Web server Servlet request request + response Servlet request + response Servlet response

34 34 More on Servlet Chaining Example use: –Servlet #1: Translates XSQL page to XML page –Servlet #2: Translates XML to HTML using XSL Can Servlet chaining be implemented using RequestDispatcher.forward? Can Servlet chaining be implemented using RequestDispatcher.include? How can Servlet chaining be implemented?

35 35 Comparison Comparing Servlets to Other Technologies

36 36 Comparing Servlets to Applets An Applet is a Java application, embedded in a Web page Commonly used for: games, graphics, etc. To add an Applet to a web page, use the tag When a browser loads the Web page, the applet byte-code is downloaded to the client box and executed by the browser

37 37 Problems with Applets Security Restrictions: Applets cannot access files or databases The Bandwidth Problem: As your applets grow in size, the download time becomes unacceptable Compatibility: –client must have a compatible browser –If a client's browser is not compatible, s/he will not be presented with proper content –Thin clients do not support the whole Java API

38 38 Servlet Solutions Why don't Servlets have: –Security restrictions? –Bandwidth problems? –Compatibility problems? What disadvantages do Servlets have over Applets?

39 39 Comparing Servlets to CGI Common Gateway Interface (CGI): Perl scripts that generate Web pages dynamically by processing form data With CGI, each request causes a new process to be created that runs the script With Servlets, each request causes a new thread to be created Thread creation requires less time and resources

40 40 Java Server Pages (JSP) JavaServer Pages: use XML-like tags and scriptlets written in Java within a web page Result in dynamic data in web page JSP is automatically compiled to Servlet Next Week: Learn about JSP!


Download ppt "1 Servlets – Part 2 Representation and Management of Data on the Web."

Similar presentations


Ads by Google