COMP201 Java Programming Part III: Advanced Features Topic 15: Servlets Materials Based on The Java Tutorial

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.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
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.
Servlets Stoney Jackson
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
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.
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.
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.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
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.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class.
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.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
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.
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.
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,
SERVLET THETOPPERSWAY.COM
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Java Servlets 9/18/2018.
Distributed Computing, M. L. Liu
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.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Presentation transcript:

COMP201 Java Programming Part III: Advanced Features Topic 15: Servlets Materials Based on The Java Tutorial

COMP201 Topic 15 / Slide 2 Outline l Introduction l A simple servlet l General information about servlets l HTTP Servlets l Session tracking and cookies l Running servlets

COMP201 Topic 15 / Slide 3 Introduction l Servlets are modules that extend (Java-enabled web) servers. n E.g. Respond to client requests by consulting a database l Most widely used within HTTP servers. Duke’s Book store

COMP201 Topic 15 / Slide 4 Introduction l Traditionally, HTTP servers handle client requests by using CGI (common gateway interface) scripts. 1. User fills out a form and submit. 2. HTTP server gets URL requests from the net. 3. HTTP server finds the CGI script specified in the HTML file, runs it with parameters from requesting URL 4. HTTP server takes output from the CGI program (most often output is HTML text), fixes it up with a full complete HTTP header, and sends it back to the original requesting client HTML: First Name: Last Name:

COMP201 Topic 15 / Slide 5 Introduction l Advantages of servlets (over CGI scripts) n More efficient –VM always running, servlet objects persist instead of being continually created/destroyed as CGI processes are n More secure –SecurityManager can constrain servlets in manner similar to applets n Portable: written in Java, while CGI scripts in C, Perl, shell script … n State-conscious –Can track session information easily. n Can access vast Java packages such as networking, threads, etc.

COMP201 Topic 15 / Slide 6 Servlet vs. Applet l Servlets are to servers what applets are to browsers: small Java programs compiled to bytecode that can be loaded dynamically and that extend the capabilities of the host. l But: l Applets run by browser, servlets run by server. l Applets are “client-side java”, servlets are “server-side java”. l Applets makes appearance of web pages alive, servlets makes contents of web pages dynamic. l Unlike applets, however, servlets have no graphical user interface. Implement only back-end processing.

COMP201 Topic 15 / Slide 7 A Simple Servlet import java.io.*; import javax.servlet.*; public class SimpleGenericServlet extends GenericServlet { public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Hello World"); out.close(); } Note: no main method. Servlet run by server, just as applet run by browser

COMP201 Topic 15 / Slide 8 A Simple Servlet service : The most important method in a servlet, Determines what the servlet does. Invoked automatically when a request comes in. Needs to be overridden. l It takes two arguments: service (ServletRequest request, ServletResponse response) ServletRequest and ServletResponse are interfaces defined by the javax.servlet Get information about a request from the ServletRequest object request. Get information about a response via the ServletResponse object response.

COMP201 Topic 15 / Slide 9 General Information about Servlets Architecture of package javax.servlet Servlet interface: declares servlet methods ( init, service, etc.) GenericServlet implements Servlet HttpServlet subclass adds features specific to HTTP Technically, a servlet is a program that extends either GenericServlet or HttpServlet.

COMP201 Topic 15 / Slide 10 General Information about Servlets Servlet Life Cycle l Servlets are controlled by servers 1. A server loads and initializes the servlet 2. The servlet handles zero or more client requests 3. The server terminates the servlet

COMP201 Topic 15 / Slide 11 Servlet Life Cycle l Methods public void init(): Called only once when servlet is being created. Good place for set up, open Database, etc. public void service(): Called once for each request. In HttpServlet, it delegates requests to doGet, doPost, etc. l public void destroy(): Called when server decides to terminate the servlet. Release resources.

COMP201 Topic 15 / Slide 12 HTTP Servlets Subclasses of javax.servlet.http.HttpSerlvet l For HTTP requests. l HTTP requests include l GET, conditional GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS l The default is GET. l Type of request specified in HTML file: …

COMP201 Topic 15 / Slide 13 HTTP Servlets Classes and interfaces in javax.servlet.http include l HttpServlet extends GenericServlet l HttpServletRequest extends ServletRequest l HttpServletResponse extends ServletResponse l … HttpServlet class has already overridden the service method to delegate requests to special purpose methods such as doGet and doPost. Don’t override the service method when sub classing HttpServlet. Instead, refine the special purpose methods, mostly doGet and doPost.

COMP201 Topic 15 / Slide 14 HTTP Servlets Methods of HttpServlet and HTTP requests All methods take two arguments: an HttpServletRequest object and an HttpServletResponse object. Return a BAD_REQUEST (400) error by default. MethodsHTTP RequestsComments doGet GET, HEADUsually overridden doPost POSTUsually overridden doPut PUTUsually not overridden doOptions OPTIONSAlmost never overridden doTrace TRACEAlmost never overridden

COMP201 Topic 15 / Slide 15 HttpServletRequest Objects l Provide access to HTTP header data and the arguments of the request. l Values of individual parameters getParameterNames method provides the names of the parameters getParameter method returns the value of a named parameter. getParameterValues method returns an array of all values of a parameter if it has more than one values. l Parameters and their values comes as a stream. Need to parse yourself. For HTTP GET requests, getQueryString method returns a String of raw data from the client. l For HTTP POST, PUT, and DELETE requests, getReader method returns a BufferedReader for reading text raw data. getInputStream method returns a ServletInputStream for reading binary raw data HTTP Servlets

COMP201 Topic 15 / Slide 16 HttpServletResponse Objects l Provide two ways of returning data to the user: getWriter method returns a PrintWriter for sending text data to client getOutputStream method returns a ServletOutputStream for sending binary data to client. Need to close the Writer or ServletOutputStream after you send the response. l HTTP Header Data Must set HTTP header data before you access the Writer or OutputStream. HttpServletResponse interface provides methods to access the header data. For example, the setContentType method sets the content type. (This header is often the only one manually set.) HTTP Servlets

Handling GET requests : Override the doGet method 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(); out.println(...); // then write the response //Get the identifier of the book from request String bookId = request.getParameter("bookId"); if (bookId != null) { out.println( information about the book );} out.close(); …… Try getRequest.html and getRequest2.html BookDetailServlet.java in bookstore example

Handling POST requests: Override the doGPost method 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(); out.println(...); // then write the response out.println(" Thank you for … " + request.getParameter("cardname") +...); out.close(); } Try postRequest.html ReceiptServlet.java in bookstore example

COMP201 Topic 15 / Slide 19 Session Tracking Motivation In the Duke’s Bookstore example, suppose a client has selected several books. (Do this and check the page produced by CatalogServlet.) l Problem 1: l The client requests ShowCartServlet to show the books in his/her shopping cart. Or CashierSerlvet to buy the books. Question: How do ShowCartServlet or CashierSerlvet know the selected books? l Problem 2: l The client decides to leave the bookstore and visit some other pages. l Question: When the client comes back and makes further requests, how do the servlets know the books that have been selected previously?

COMP201 Topic 15 / Slide 20 Session Tracking l Session tracking is a mechanism that servlets use to maintain state about a series of requests l From the same user (that is, requests originating from the same browser) l Across some period of time (30 minutes for the Java Web Server). Solution to Problem 2. l Sessions are shared among the servlets accessed by the same client. Solution to Problem 1.

COMP201 Topic 15 / Slide 21 Session Tracking To use session tracking, Get a session (a HttpSession object) from the request. HttpSession getSession(boolean create) HttpSession session = request.getSession(true); Do this before accessing response streams. Store or get data from the HttpSession object. public void putValue(String name, Object obj) public Object getValue(String name). l Invalidate the session (optional). Manually : Session.invalidate() Automatically when no request after certain time.

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); HttpSession session = req.getSession(false); PrintWriter out = resp.getWriter(); out.println(" Count me! "); if (session == null) {out.println("Welcome, I don't believe we've met!"); session = req.getSession(true); session.putValue("Count", new Integer(1)); out.println(”I think of you as "+ session.getId()); } else {int n=((Integer)session.getValue("Count")).intValue(); out.println("You again? ” + session.getId()); out.println(”That makes " + n + " visits!”); session.putValue("Count", new Integer(n + 1)); } out.println(" "); out.close(); } // HelloAgainServlet.java

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getValue(session.getId()); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putValue(session.getId(), cart);} //Only one piece of data // set content-type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(…) // then write the data of the response

CatalogServlet.java // Additions to the shopping cart String bookToAdd = request.getParameter("Buy"); if (bookToAdd != null) { BookDetails book = frontEnd.getBookDetails(bookToAdd); cart.add(bookToAdd, book); …. // add book to cart }

COMP201 Topic 15 / Slide 25 Cookies l A way for servlet to send some information to client for storage and later retrieval. Each cookie is a name=value pair. l Servlets send cookies to clients by adding fields to HTTP response headers. l Clients automatically return cookies by adding fields to HTTP request headers. l Cookies returned to a server. Cookies shared among servlets on the server accessed by the same client. l Cookies can be used for Session tracking. HttpSession implemented using cookies. l Persistent state. E.g. name, address, address. When user access some servlets again, no need to provide such information one more time.

COMP201 Topic 15 / Slide 26 Cookies Cookies are objects of class javax.servlet.http.Cookie l To send a cookie, 1. Create a Cookie object Cookie c = new Cookie(name, value); 2. Set attributes if necessary c.setMaxAge(30); // expire after 30 seconds 3. Send the cookie response.addCookie(c); l To get information from a cookie, 1. Retrieve all the cookies from the user's request Cookie[] cookies = request.getCookies(); 2. Find the cookie that you are interested in and get its value for (int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Cookies received from client: "); Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value + " "); } out.println(" Cookies sent to client:> "); String name = request.getParameter("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); c.setMaxAge(30); response.addCookie(c); out.println(name + " = " + value + " "); }} // CookieServlet.java

COMP201 Topic 15 / Slide 28 Running Servlets 1. Download and install Java Servlet development kit Several versions are available: JSDK 2.0, JSDK 2.1, and Java Servlet 2.3. We will use JSDK Compile servlet 3. Configure server for servlets 4. Place servlet at appropriate location 5. Call it from browser or HTML file

COMP201 Topic 15 / Slide 29 Running Servlets l Download JavaServer Web Development kit JSWDK1.0.1 from A package that contains JavaServer Pages and the JSDK 2.1 l Installation instructions for Solaris (TA will discuss installation for Windows): l Uncompress the file obtained to get a tar file. Expand the tar file. You will get a subdirectory zzz/jswdk , where zzz is the directory where you keep the tar file. The subdirectory contains all files in the JSWDK1.0.1 package. Add two ".jar " files into the classpath in.cshrc_user : zzz/jswdk-1.0.1/lib/servlet.jar, zzz/jswdk-1.0.1/webserver.jar Now we should be able to compile SimpleGenericSerlvet.java using javac

COMP201 Topic 15 / Slide 30 Compiling and Running Servlets Configure server for servlets: l By system administrator for standard HTTP servers l We will use the HTTP server that comes with JSDK 2.1 Setting servlet properties: Modify file zzz/jswdk-1.0.1/webpages/WEB-INF/servlets.properties 1. Name servlet (for convenience) simple.code=SimpleGenericServlet 2. Initialize parameters required by servlet l Starting and stopping server zzz/jswdk-1.0.1/startserver zzz/jswdk-1.0.1/stopserver l Notes: 1. By default, server runs on localhost at port Document root at zzz/jswdk-1.0.1/webpages 3. Can change those in zzz/jswdk-1.0.1/webserver.xml

COMP201 Topic 15 / Slide 31 Compiling and Running Servlets l Accessing the server 1. Web pages should be placed under document root. 2. Servlets (class files) should be placed under Document root/WEB-INF/servlets/. Example: Place SimpleGenericServlet.class under the servlets subdirectory and you can access it from browser: or l NOTE: When client requests a servlet, server creates a servlet object. The object hangs around until server stops its (which usually happens when server shuts down). To reload a servlet, stop and restart server! (This is the limitation of the HTTP server that comes with JSDK 2.1. Normal web servers reload modified servlets automatically)

COMP201 Topic 15 / Slide 32 Running Servlets One can call servlets by the following ways: l Calling a servlet directly by typing the URL into a browser’s location window l Calling servlets from an HTML page by put the URL in HTML Tags: l Check Out l l Calling Servlets from Servlets: 1. Make an Http request of another servlet 2. Call another servlet’s public methods directly, if the two servlets run within the same server: BookDBServlet database = (BookDBServlet) getServletConfig().getServletcontext(). getServlet(“bookdb”);