Distributed Computing, M. L. Liu

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
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.
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.
An introduction to Java Servlet Programming
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.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
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.
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
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.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
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.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
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.
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
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.
Java Servlets & Java Server Pages Lecture July 2013.
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.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
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.
Servlets.
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.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Java Servlets Java Server Pages (JSP)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Cookies in Servlet A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value,
SERVLET THETOPPERSWAY.COM
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:
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlets.
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
JDBC & Servlet CSE 4504/6504 Lab.
Pre-assessment Questions
HTTP Servlet Overview Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might.
Java Servlets 9/18/2018.
Java Servlets 9/21/2018.
Servlet.
Chapter 26 Servlets.
Distributed Computing, M. L. Liu
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Objectives In this lesson you will learn about: Need for servlets
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Java Servlets Servlet Overview Servlets and HTML Forms Servlet Basics
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Pre-assessment Questions
Presentation transcript:

Distributed Computing, M. L. Liu Java Servlets M. L. Liu 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Introduction Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. Servlets are to servers what applets are to browsers: an external program invoked at runtime. Unlike applets, however, servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol. Servlets are portable. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Servlet Basics A servlet is an object of the javax.servlet class. It runs inside a Java Virtual Machine on a server host. Unlike applets, servlets do not require special support in the web browser. The Servlet class is not part of the Java Development Kit (JDK). You must download the JDSK (Java Servlet Development Kit). A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Uses for Servlets http://java.sun.com/docs/books/tutorial/servlets/overview/index.html Providing the functionalities of CGI scripts with a better API and enhanced capabilities. Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing.   Forwarding requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.   9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Generic Servlets and HTTP Servlets Java Servlet Programming, O’Reilley Press Every servlet must implement the javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet javax.servlet.http.HttpServlet A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ) and/or doGet( ) method. 9/19/2018 Distributed Computing, M. L. Liu

Generic and HTTP Servlets 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu A simple Servlet, from http://java.sun.com/docs/books/tutorial/servlets/overview/simple.html public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); } 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Using HTTP Servlet to process web forms http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html Requests and Responses Methods in the HttpServlet class that handle client requests take two arguments: An HttpServletRequest object, which encapsulates the data from the client   An HttpServletResponse object, which encapsulates the response to the client public void doGet (HttpServletRequest request, HttpServletResponse response) public void doPost(HttpServletRequest request, HttpServletResponse response) 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu HttpServletRequest Objects http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. The HttpServletRequest object also allows you to obtain the arguments that the client sent as part of the request. To access client data:   The getParameter method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues instead. The getParameterValues method returns an array of values for the named parameter. (The method getParameterNames provides the names of the parameters.)   For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values.  9/19/2018 Distributed Computing, M. L. Liu

HttpServletRequest Interface public String ServletRequest.getQueryString( ); returns the query string of the requst. public String GetParameter(String name): given the name of a parameter in the query string of the request, this method returns the value. String id = GetParameter(“id”) public String[ ] GetParameterValues(String name): returns multiple values for the named parameter – use for parameters which may have multiple values, such as from checkboxes. String[ ] colors = req.getParmeterValues(“color”); if (colors != null) for (int I = 0; I < colors.length; I++ ) out.println(colors[I]); public Enumeration getParameterNames( ): returns an enumeration object with a list of all of the parameter names in the query string of the request. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu HttpServletResponse Objects http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletResponse object provides two ways of returning data to the user:   The getWriter method returns a Writer   The getOutputStream method returns a ServletOutputStream   Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete.   9/19/2018 Distributed Computing, M. L. Liu

HttpServletResponse Interface public interface HttpServletResponse extends ServletResponse: “The servlet engine provides an object that implements this interface and passes it into th servlet through the service method” – “Java Server Programming” public void setContentType(String type) : this method must be called to generate the first line of the HTTP response: setContentType(“text/html”); public PrintWriter getWriter( ) throws IOException: returns an object which can be used for writing the responses, one line at a time: PrintWriter out = res.getWriter; out.println(“<h1>Hello world</h1>”); 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Servlets are Concurrent servers http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html HTTP servlets are typically capable of serving multiple clients concurrently. If the methods in your servlet do work for clients by accessing a shared resource, then you must either:   Synchronize access to that resource, or   Create a servlet that handles only one client request at a time.  9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Handling GET requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http-methods.html public class BookDetailServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content-type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();  // then write the response out.println("<html>" + "<head><title>Book Description</title></head>" + ... );  //Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // fetch the information about the book and print it ... } out.println("</body></html>"); out.close(); } ...} 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Handling POST Requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http-methods.html public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter( ); // then write the response out.println("<html>" + "<head><title> Receipt </title>" + ...); out.println("Thank you for purchasing your books from us " + request.getParameter("cardname") + ...); out.close(); } 9/19/2018 Distributed Computing, M. L. Liu

The Life Cycle of an HTTP Servlet The web server loads a servlet when it is called for in a web page. The web server invokes the init( ) method of the servlet. The servlet handles client responses. The server destroys the servlet (at the request of the system administrator). A servlet is normally not destroyed once it is loaded. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Servlet Examples See Servlet\simple folder in code sample: HelloWorld.java: a simple servlet Counter.java: illustrates that a servlet is persistent Counter2.java: illustrates the use of synchronized method with a servlet GetForm.html, GetForm.java: illustrates the processing of data sent with an HTTP request via the GET method PostForm.html, PostForm.java: illustrates the processing of data sent with an HTTP request via the POST method 9/19/2018 Distributed Computing, M. L. Liu

Session State Information The mechanisms for state information maintenance with CGI can also be used for servlets: hidden-tag, URL suffix, file/database, cookies. In addition, a session tracking mechanism is provided, using an HttpSession object. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Cookies in Java http://java.sun.com/products/servlet/2.2/javadoc/index.html A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servelet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies( ) method. Several cookies might have the same name but different path attributes. 9/19/2018 Distributed Computing, M. L. Liu

Processing Cookies with Java Java Server Programming – Wrox press A cookie is an object of the javax.servlet.http.cookie class. Methods to use with a cookie object: public Cookie(String name, String value): creates a cookie with the name-value pair in the arguments. import javax.servlet.http.* Cookie oreo = new Cookie(“id”,”12345”); public string getName( ) : returns the name of the cookie public string getValue( ) : returns the value of the cookie public void setValue(String _val) : sets the value of the cookie public void setMaxAge(int expiry) : sets the maximum age of the cookie in seconds. 9/19/2018 Distributed Computing, M. L. Liu

Processing Cookies with Java – 2 Java Server Programming – Wrox press public void setPath(java.lang.String uri) : Specifies a path for the cookie to which the client should return the cookie. The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog. public java.lang.String getPath() : Returns the path on the server to which the browser returns this cookie. The cookie is visible to all subpaths on the server. public String getDomain( ) : returns the domain of the cookie. if orea.getDomain.equals(“.foo.com”) … // do something related to golf public void setDomain(String _domain): sets the cookie’s domain. 9/19/2018 Distributed Computing, M. L. Liu

doGet Method using cookies public void doGet(HttpServletResponse req, HttpServletResponse res) throws ServletException, IOExceiption{ res.setContentType(“text/html”); PrintWriter out = res.getWriter( ); out.println (“<H1>Contents of your shopping cart:</H1>”); Cookie cookies[ ]; cookies = req.getCookies( ); if (cookies != null) { for ( int i = 0; i < cookies.length; i++ ) { if (cookies[i].getName( ).startWith(“Item”)) out.println( cookies[i].getName( ) + “: “ + cookies[i].getValue( )); out.close( ); } 9/19/2018 Distributed Computing, M. L. Liu

Servlet & Cookies Example See Servlet\cookies folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a cookie object for each items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to scan cookies received with the HTTP request and display the contents of each cookie. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu HTTP Session Objects http://java.sun.com/products/servlet/2.2/javadoc/index.html The javax.servlet.http package provides a public interface HttpSession: Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu HTTP Session Object - 2 http://java.sun.com/products/servlet/2.2/javadoc/index.html This interface allows servlets to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections Session object allows session state information to be maintained without depending on the use of cookies (which can be disabled by a browser user.) Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu The Session object 9/19/2018 Distributed Computing, M. L. Liu

Obtaining an HTTPSession Object A session object is obtained using the getSession( ) method of the HttpServletRequest object (from doPost or doGet) public HTTPSession getSession(boolean create): Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed. public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletRespnse res) throws ServletException, IOException … // get session object HttpSession session = req.getSession(true) if (session != null) { } … 9/19/2018 Distributed Computing, M. L. Liu

The HTTPSession Object methods public java.lang.String getId( ): returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent. public java.lang.Object getAttribute(java.lang.String name): returns the object bound with the specified name in this session, or null if no object is bound under the name. public java.util.Enumeration getAttributeNames( ): returns an Enumeration of String objects containing the names of all the objects bound to this session. public void removeAttribute(java.lang.String name): removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing. 9/19/2018 Distributed Computing, M. L. Liu

Session Object example See Servlet\Session folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a session object which contains descriptions of items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to display items in the shopping cart, as recorded by the use a session object in the Cart servlet 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Summary - 1 A servlet is a Java class. Its code is loaded to a servlet container on the server host. It is initiated by the server in response to a client’s request. Once loaded, a servlet is persistent. 9/19/2018 Distributed Computing, M. L. Liu

Distributed Computing, M. L. Liu Summary - 2 For state information maintenance: hidden form fields cookies the servlet’s instance variables may hold global data a session object can be used to hold session data 9/19/2018 Distributed Computing, M. L. Liu