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

Slides:



Advertisements
Similar presentations
JSP and Servelets.
Advertisements

CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
Java Server Pages (JSP)
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
CSE 190: Internet E-Commerce Lecture 7. HTML Templates Designed to separate server side logic from HTML presentation Key features –Escapes from HTML into.
An introduction to Java Servlet Programming
J2EE Servlets and JSP Advanced topics Presented by Bartosz Sakowicz.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
1 Servlets Part 2 Representation and Management of Data on the Web.
Servlet Session Tracking. 2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information.
Integrating Servlets and JavaServer Pages Vijayan Sugumaran School of Business Administration Oakland University Parts of this presentation provided by.
1 CS6320 – Servlet Cookies L. Grewe 2 What is a cookie? Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser.
/ department of mathematics and computer sciencedepartment of mathematics and computer science / architecture of information systems.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
Session Tracking - 2 Lec 32. Last Lecture Review  Session Tracking – why?  Need to store state – typical solutions Cookies – already learned URL Rewriting.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
Java Servlets Java Server Pages (JSP)
Vakgroep Informatietechnologie – Onderzoeksgroep (naam) Web Centric Design of Distributed Software.
©SoftMooreSlide 1 Session Tracking with Servlets.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
Session Tracking Parts of this presentation was provided by SSE.
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Java Servlets 9/18/2018.
Java Servlets 9/21/2018.
Sessions.
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Pre-assessment Questions
Modified slides from Dr.Sagiv
Presentation transcript:

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

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

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 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 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 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 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 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 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 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 Login Page Logon to My Site Your Name: HTML Page

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 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 Using Cookies: Intuition sessionIdsessionData dsf jlsdf 234jksdf dd …… …… …… …… …… …… …… …… …… …… …… ……

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 URL Encoding Client appends some extra data to all URLs of the session: – 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 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 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 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 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 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 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 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 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 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 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 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 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 public class Travel extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String Address = request.getParameter(" Address"); String password = request.getParameter("password"); TravelCustomer customer = TravelCustomer.findCustomer(password, Address); 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 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 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 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 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 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 Comparison Comparing Servlets to Other Technologies

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 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 Servlet Solutions Why don't Servlets have: –Security restrictions? –Bandwidth problems? –Compatibility problems? What disadvantages do Servlets have over Applets?

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 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!