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

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
Advertisements

6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Dispatching, monitoring, filtering
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.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….) Representation and Management of Data on the Internet, 2007 CS Department, HUJI.
1 CS6320 – Servlet Request Dispatcher L. Grewe 2 What is the purpose Forward a request from one servlet to another (or jsp). Forward a request from one.
Servlets Stoney Jackson
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.
1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….)
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.
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 Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
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.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
3/26/2003Servlet Security 1 CSCI Research Topics in Computer Science --Web Security Instructor: Dr.Yang Students: Shiyou Li, Gang Zheng.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
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.
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.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
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.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)
1 Uploading Files with Servlets Read more about the FileUpload APIFileUpload API.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Representation and Management of Data on the Internet, 2007
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
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:
Servlet Filters JAVA Enterprise Edition. Servlet Filters Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
©SoftMooreSlide 1 Session Tracking with Servlets.
Java and the Web CSE 3330 Southern Methodist University.
Session Tracking Parts of this presentation was provided by SSE.
Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory.
Introduction To HTML Dr. Magdi AMER. HTML elements.
1 Servlets Part 2 Representation and Management of Data on the Web.
1 Servlets – Part 2 Representation and Management of Data on the Web.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Servlet V.B.Sanghavi. Overview of Servlet to create web application resides at server side and generates dynamic web page V.B.Sanghavi.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre assessment Questions
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Java Servlets 9/18/2018.
Java Servlets 9/21/2018.
Sessions.
Servlets and Java Server Pages
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.
Knowledge Byte In this section, you will learn about:
Pre-assessment Questions
Modified slides from Dr.Sagiv
Presentation transcript:

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

2 Servlets and Cookies Cookie Example

3 Servlets and Cookies Java Servlet API provides comfortable mechanisms to handle cookies The class javax.servlet.http.Cookie represents a cookie -Getter methods: getName(), getValue(), getPath(), getDomain(), getMaxAge(), getSecure() … -Setter methods: setValue(), setPath(), setDomain(), setMaxAge() …

4 Servlets and Cookies (cont) Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response: HttpServletResponse.addCookie(Cookie cookie)

5 An Example Insert your Name What is your name? getname.html

6 An Example (cont) public class WelcomeBack extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("username"); if (user == null) { // Find the "username" cookie Cookie[] cookies = req.getCookies(); for (int i = 0; cookies != null && i < cookies.length; ++i) { if (cookies[i].getName().equals("username")) user = cookies[i].getValue(); } } else res.addCookie(new Cookie("username", user)); WelcomeBack.java

7 An Example (cont) if (user == null) // No parameter and no cookie res.sendRedirect("getname.html"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Welcome Back " + user + " "); } WelcomeBack.java

8 Session Management with Servlets

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

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

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

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

13 sessionId list

14 Accessing the Session Data The session object is represented by the class HttpSession Use the methods getSesssion() or getSession(true) of the doXXX request to get the current HttpSession 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 getSession(false) if you do not want to create a new session when no session exists

15 HttpSession Methods Session data is accessed in a hash-table fashion: -setAttribute(String name,Object value) -Where is this value stored? -Object getAttribute(String name) More methods: -removeAttribute, getAttributeNames -isNew, invalidate, getId -getCreationTime, getLastAccessedTime -getMaxInactiveInterval, setMaxInactiveInterval

16 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 -ShoppingCart.java: handles cart manipulation

17 Online-Store Example public class Store extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" " + "<link rel=\"stylesheet\" type=\"text/css\"" + " href=\"cartstyle.css\"/> "); HttpSession session = req.getSession(); if (session.getAttribute("item-list") == null) { out.println(" Hello new visitor! "); session.setAttribute("item-list", new LinkedList()); } List itemList = (List) session.getAttribute("item-list"); Store.java

18 Online-Store Example (cont) out.println(" Your Shopping Cart: "); for (Iterator it = itemList.iterator(); it.hasNext();) out.println(" " + it.next() + " "); out.println(" "); out.println(" Add item: " + " " + " <input type=\"submit\" value=\"empty cart\" " + "name=\"clear\"/> "); out.println(" "); } Store.java

19 Online-Store Example (cont) public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); List items = (List) req.getSession().getAttribute("item-list"); out.println(" <link rel=\"stylesheet\"" + " type=\"text/css\" href=\"cartstyle.css\"/>" + " "); ShoppingCart.java

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

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

22 URL Rewriting Web server request Servlet id 1 response request (no cookie) id 2 Session read/write Web browser 1 GET servletURL;sessID=id 1 HTTP/1.0 … …

23 Servlet URL Rewriting Use the following methods of the doXXX response object to rewrite URLs: -String encodeURL(String url) Use for HTML hyperlinks -String encodeRedirectURL(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

24 Back to our Store The Store example assumes that the client supports cookies To fix the program, we should encode the links we supply: Store.java: "<form method=\"post\" action=\"" + res.encodeURL("cart") + "\">" ShoppingCart.java: “ "

25 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.HttpSessionListener

26 Session-Listener Example (cont) public class CartInitializer implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { List itemList = new LinkedList(); se.getSession().setAttribute("item-list",itemList); itemList.add("A Free Apple"); } public void sessionDestroyed(HttpSessionEvent se) {} } CartInitializer.java CartInitializer web.xml

27 The Servlet Context

28 Uses of ServletContext For communicating with the Servlet container (e.g., Tomcat server), we use the ServletContext 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

29 ServletContext Methods Access initialization parameters: getInitParameter(String name), getInitParameterNames() Read Web-application attributes: getAttribute(String name), getAttributeNames() Manipulate Web-application attributes: setAttribute(String, Object), removeAttribute(String) Transform context-relative paths to absolute paths: getRealPath(String path), URL getResource(String path)

30 ServletContext Methods Write to the application log: log(String msg), log(String message, Throwable exception) Get a resource dispatcher (discussed later): RequestDispatcher getRequestDispatcher(String path) Name and version of the Servlet container: String getServerInfo()

31 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 You can lock the context to protect a critical section from all Web-application accesses

32 The Request Dispatcher

33 The Request Dispather The RequestDispatcher 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: getServletContext().getRequestDispatcher("x")

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

35 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.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 every client context.setAttribute("key", value);

36 An Example The Servlet JokesAndImages 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/

37 Jokes and Images Images and Jokes Please Select: <input type="submit" name="joke" value="A Joke" /> <input type="submit" name="image" value="An Image" /> imagesJokesOptions.html

38 Jokes and Images (cont) public class JokesAndImages extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int randomNum = 1 + Math.abs((new Random()).nextInt() % 5); if (req.getParameter("joke") != null) { req.setAttribute("jokeNumber", new Integer(randomNum)); getServletContext().getRequestDispatcher("/Jokes").forward(req,res); } else if (req.getParameter("image") != null) { getServletContext().getRequestDispatcher("/images/image" + randomNum + ".gif").forward(req, res); } else getServletContext().getRequestDispatcher ("/imagesJokesOptions.html"). forward(req,res); } public void doGet... }} JokesAndImages.java

39 Jokes and Images (cont) public class Jokes extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" A Joke "); int jokeNum = ((Integer) req.getAttribute("jokeNumber")).intValue(); getServletContext().getRequestDispatcher ("/jokes/joke" + jokeNum + ".txt").include(req, res); out.println("\n "); out.println(" Back "); out.println(" "); }} Jokes.java

40 Forwarding versus Redirection SendRedirect requires extra communication on part of the client: Why? By default, SendRedirect does not preserve parameters of the request SendRedirect ends up with a different URL on the client Which image will be loaded in the following scenario? Servlet /a forwards to /jokes/joke1.html and joke1.html includes

41 Programmatic Security with Servlets

42 Programmatic-Security Methods Servlet API contains several accessories for handling programmatic security: - getRemoteUser() - isUserInRole(String role) - getAuthType() These are all methods of HttpServletRequest To enable user authentication (even for public URLs), provide a link to some protected page

43 An Example: Security Constraints in web.xml Firm People /login.html employees managers web.xml

44 FORM /login /login?fail=fail managers employees web.xml An Example: Security Constraints in web.xml

45 public class FirmServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Firm "); out.println(" Hello. "); String username = req.getRemoteUser(); if(username==null) { out.println(" "); out.println(" Login "); out.println(" "); return; } FirmServlet

46 if(req.isUserInRole("employees")) { out.println(" "); out.print(" Welcome Employee " + username + "! "); } if(req.isUserInRole("managers")) { out.println(" "); out.print(" Executive average salary: 42764NIS! "); } out.print(" Log Out "); out.println(" "); } FirmServlet

47 public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println(" Login "); if(req.getParameter("fail")!=null) out.print(" Login Failed. Try Again. "); out.println(" " + " Login: " + " Password: " + " " + " "); } LoginServlet.java

48 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); } LoginServlet.java Login LoginServlet Login /login web.xml

49 public class EndSession extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(false); if(session!=null) session.invalidate(); res.sendRedirect("firm"); } EndSession.java EndSession EndSession /endsession web.xml

50 Filters

51 Filters in Servlet API Filters are used to dynamically intercept requests and responses A filter that applies to a URL u typically acts as follows given a request for u -performs some actions before the processing of u -passes the request handling to the next filter -performs some actions after the processing of u

52

53 public final class FilterExample implements Filter { public void init(FilterConfig filterConfig) throws ServletException {... } public void destroy() {... } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {... chain.doFilter(request, response);... }} FilterExample.java

54 Example Filter FilterExample Example Filter /images/* Registering a Filter web.xml

55 What Can we Do with Filters? Examine and log requests Modify request headers and properties Modify the response headers and response data -E.g., by replacing the response with a wrapper -Content compression -Image conversion Block requests And more...

56 Notes About Filters The order of the filters in the chain is the same as the order that filter mappings appear web.xml The life cycle of filters is similar to that of Servlets Filters typically do not themselves create responses, although they can The request and response arguments of doFilter are actually of type HttpServletRequest and HttpServletResponse The filterConfig is used to read initialization parameters -Those are set in web.xml