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

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
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.
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
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
CS320 Web and Internet Programming Handling HTTP Requests Chengyu Sun California State University, Los Angeles.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 Servlets Representation and Management of Data on the Web.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
1 CS6320 – Servlet Request and Response L. Grewe.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
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 Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
Servlets Life Cycle. The Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. The following.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
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.
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,
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.
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.
Running Servlets JSDK2.1 default.cfg : Web Server configuration information batch files to start and stop server Servlet properties in /webpages/WEB-INF.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Threading Servlets Can handle multiple clients concurrently Shared resources must be synchronized or create a servlet that handles one request at a time.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
1 Servlets Modified slides from Dr.Sagiv. 2 Introduction.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
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.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
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.
Representation and Management of Data on the Web
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Server-Side Programming 1cs What is a Servlet A Java application that is being run by a Web server Can receive parameters in an HTTP request Generates.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
1 Servlets Sun tutorial to servletstutorial to servlets.
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Chapter 4 Request and Response. Servlets are controlled by the container.
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.
Distributed Web Systems Java Servlets Lecturer Department University.
CS122B: Projects in Databases and Web Applications Spring 2017
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlet Fudamentals.
HTTP request message two types of HTTP messages: request, response
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
CS122B: Projects in Databases and Web Applications Spring 2018
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.
CS122B: Projects in Databases and Web Applications Winter 2019
Basic servlet structure
Presentation transcript:

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

2 Introduction

3 Static Pages Web browser Web server request response

4 Dynamic Pages Web browser Web server request response Servlet JSP ASP Servlet JSP ASP

5 What is a Servlet? Servlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an intermediating layer between an HTTP request of a client and the Web server

6 An Example In the following example, the local server calls the Servlet TimeServlet with an argument supplied by the user This example, as well as all the examples in this lecture can be found at (accessible only from CS!)

7

8

9 What do Servlets do? Read data sent by the user (e.g., form data) Look up other information about request in the HTTP request (e.g. authentication data, cookies, etc.) Generate the results (may do this by talking to a database, file system, etc.) Format the results in a document (e.g., make it into HTML) Set the appropriate HTTP response parameters (e.g. cookies, content-type, etc.) Send the document to the user

10 Supporting Servlets The Web server must support Servlets (since it must run the Servlets): -Apache Tomcat -Sun’s Java System Web Server and Java System Application Server - IBM's WebSphere Application Server -Allaire Jrun – an engine that can be added to IIS, PWS, old Apache Web servers etc… -Oracle Application Server -… In your final project you will install this server to create a powerful website

11 Creating a Simple Servlet

12 The Servlet Interface Java provides the interface Servlet Specific Servlets implement this interface Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet service(request,response) MyServlet (HTTP) request (HTTP) response

13 HTTP Request Methods POST - application data sent in the request body GET - application data sent in the URL HEAD - client sees only header of response PUT - place documents directly on server DELETE - opposite of PUT TRACE - debugging aid OPTIONS - list the methods available on page

14 Servlet Hierarchy YourOwnServlet HttpServlet Generic Servlet Servlet service(ServletRequest, ServletResponse) doGet(HttpServletRequest, HttpServletResponse) doPost(HttpServletRequest HttpServletResponse) doPut doTrace …

15 Class HttpServlet Class HttpServlet handles requests and responses of HTTP protocol The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: doGet, doPost, doPut, doDelete, doTrace, doOptions or doHead This class is abstract

16 Creating a Servlet Extend the class HTTPServlet Implement doGet or doPost (or both) Both methods get: - HttpServletRequest : methods for getting form (query) data, HTTP request headers, etc. - HttpServletResponse : methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client Usually implement doPost by calling doGet, or vice-versa

17 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TextHelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Hello World"); out.close(); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); }

18

19 Returning HTML By default a text response is generated In order to generate HTML -Tell the browser you are sending HTML, by setting the Content-Type header -Modify the printed text to create a legal HTML page You should set all headers before writing the document content. Can you guess why?

20 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Hello World "); out.println(“ Hello World "); out.close(); }

21

22 Configuring the Server When your Servlet class is ready, you have to configure the Web server to recognize it This includes: -Telling the Server that the Servlet exists -Placing the Servlet class file in a place known to the server -Telling the server which URL should be mapped to the Servlet These details are server specific and are not covered in this lecture

23 Getting Information From the Request

24 An HTTP Request Example GET /default.asp HTTP/1.0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */* Accept-Language: en Connection: Keep-Alive Host: magni.grainger.uiuc.edu User-Agent: Mozilla/4.04 [en] (WinNT; I ;Nav) Cookie: SITESERVER=ID=8dac8e0455f4890da220ada8b76f; ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM Accept-Charset: iso ,*,utf-8

25 Getting HTTP Data Values of the HTTP request can be accessed through the HttpServletRequest object Get the value of the header hdr using getHeader(" hdr ") of the request argument Get all header names: getHeaderNames() Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc.

26 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers";

27 out.println(" " + title + " " + " \n" + " " + title + " \n" + " Request Method: " + request.getMethod() + " \n" + " Request URI: " + request.getRequestURI() + " \n" + " Request Protocol: " + request.getProtocol() + " \n" + " \n" + " Header Name Header Value");

28 Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName =(String)headerNames.nextElement(); out.println(" " + headerName); out.println(" “ + request.getHeader(headerName)); } out.println(" \n "); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } Execution:

29

30

31 User Input in HTML Using HTML forms, we can pass parameters to web applications … comprises a single form action: the address of the application to which the form data is sent method: the HTTP method to use when passing parameters to the application (e.g. GET or POST)

32 The Tag Inside a form, INPUT tags define fields for data entry Standard input types include: buttons, checkboxes, password field, radio buttons, text fields, image- buttons, text areas, hidden fields, etc. They all associate a single (string) value with a named parameter

33 GET Example

34 POST Example <FORM method=“POST“ action=" POST /search HTTP/1.1 Host: … Content-type: application/x-www-form-urlencoded Content-length: 10 q=servlets Google doesn’t support POST!

35 Getting the Parameter Values To get the value of a parameter named x: - req.getParameter("x") where req is the service request argument If there can be multiple values for the parameter: - req.getParameterValues("x") To get parameter names: - req.getParameterNames()

36 Sending Parameters Please enter the parameters <FORM ACTION=“SetColors” METHOD=“GET”> Background color: Font color: Font size:

37

38 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SetColors extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String bg = request.getParameter("bgcolor"); String fg = request.getParameter("fgcolor"); String size = request.getParameter("size");

39 out.println(" Set Colors Example" + " "); out.println("<BODY text='" + fg + "' bgcolor='" + bg + "'>"); out.println(" Set Colors Example "); out.println(" "); out.println("You requested a background color " + bg + " "); out.println("You requested a font color " + fg + " "); out.println("You requested a font size " + size + " "); out.println(" "); }

40

41 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } You don't have to do anything different to read POST data instead of GET data!! <FORM ACTION=“SetColors” METHOD=“POST”> … Handling Post

42 Creating the Response of the Servlet

43 HTTP Response The response includes:  Status line: version, status code, status message  Response headers  Empty line  Content HTTP/ OK Content-Type: text/html Content-Length: 89 Server: Apache-Coyote/1.1 HELLO WORLD Hello World

44 Setting the Response Status Use the following HttpServletResponse methods to set the response status: -setStatus(int sc) Use when there is no error, like 201 (created) -sendError(sc), sendError(sc, message) Use in erroneous situations, like 400 (bad request) The server may return a formatted message -sendRedirect(String location) Redirect to the new location

45 Setting the Response Status Class HTTPServletResponse has static integer variables for popular status codes -for example: SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400) Status code 200 (OK) is the default

46 Setting Response Headers Use the following HTTPServletResponse methods to set the response headers: -setHeader(String hdr, String value), setIntHeader(String hdr, int value) Override existing header value -addHeader(String hdr, String value), addIntHeader(String hdr, int value) The header is added even if another header with the same title exists

47 Specific Response Headers Class HTTPServletResponse provides setters for some specific headers: -setContentType -setContentLength automatically set if the entire response fits inside the response buffer -setDateHeader -setCharacterEncoding

48 More Header Methods containsHeader(String header) -Check existence of a header in the response addCookie(Cookie) sendRedirect(String url) -automatically sets the Location header Do not write information to the response after sendError or sendRedirect

49 The Response Content Buffer The response body is buffered Data is sent to the client when the buffer is full or the buffer is explicitly flushed Once the first data chunk is sent to the client, the response is committed -You cannot set the response line nor change the headers. Such operations are either ignored or cause an exception to be thrown

50 Buffer Related Methods setBufferSize, getBufferSize -What are the advantages of using big buffers? what are the disadvantages? flushBuffer resetBuffer -Clears the body content reset -Clears any data that exists in the buffer as well as the status code and headers isCommitted

51 Supporting HTTP Methods

52 The HEAD Method The default implementation of doHead is executing doGet and excluding the response body In addition, the size of the body is calculated and added to the headers You do not have to override this method -Why would one like to override this method?

53 OPTIONS and TRACE doOptions returns the supported methods: -For example, if you override doGet then the following header will be returned: Allow: GET, HEAD, TRACE, OPTIONS doTrace returns the request itself in the body of the message, for debugging purposes You usually do not override these methods -Override doOptions if you offer some new methods…

54 Unsupported Methods By default, the methods doPost, doGet, doPut and doDelete return an error status code 405 with the message: HTTP method XXX is not supported by this URL In particular, you have to override doGET and doPost if you want to return an appropriate response for these methods -Many applications support only one of GET/POST

55 Servlet Life Cycle

56 Servlet Life Cycle The server loads the Servlet class and initializes one instance of it Each client request is handled by the Serlvet instance in a separate thread The server can remove the servlet The servlet can remain loaded to handle additional requests

57 Servlet Life Cycle When the Servlet in instantiated, its method init is begin invoked -External parameters are supplied Upon a request, the method service of the Servlet is being invoked Before the Servlet removal, its method destroy is being invoked

58 Servlet Life Cycle Servlet Class Calling the init method Servlet Instance Deal with requests: call the service method Destroy the Servlet: call the destroy method Garbage Collection ServletConfig

59 Initializing Servlets Performed when the Servlet is loaded into the Web server Servlet’s init(ServletConfig) method is called ServletConfig has methods to get initialization parameters -Put these parameters in a file that is known to the server To make initializations, override init() - init() is automatically called by init(ServletConfig) after performing default initializations

60 … InitExample ServletInit login snoopy … A Glance at Servlet Configuration Parameters

61 import javax.servlet.http.*; import javax.servlet.*; import java.util.*; import java.io.*; public class ServletInit extends HttpServlet { String _login = null; Date _initTime = null; int _counter = 1; public void init() throws ServletException { _login = this.getInitParameter("login"); _initTime = (new GregorianCalendar()).getTime(); }

62 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { _counter = _counter + 1; PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println(" " + "[" + _counter + "] " + "I am the servlet of " + _login + " " + "I was initialized at " + _initTime.getHours() + ":" + _initTime.getMinutes() + ":" + _initTime.getSeconds() + " "); out.close(); }

63

64

65 Thread Synchronization Multiple threads are accessing the same Servlet object at the same time Therefore, you have to deal with concurrency init() and destroy() are guaranteed to be executed only once (before/after all service executions) What was wrong in the code of ServletInit ?

66 Solving Synchronization Problems Synchronize a code block: synchronized(this) { _counter = _counter + 1; localCounter = _counter; } Synchronize the service: public synchronized void doGet(HttpServletRequest req, HttpServletResponse res) -Why is this a bad solution?

67 The Revised Code public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int localCounter = 0; synchronized(this) { _counter = _counter + 1; localCounter = _counter; } PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println(… + "[" + localCounter+ "] " + …); out.close(); } }

68 Single Thread Model in History In older Servlet versions, you could enforce maintenance of several Servlet instances, each guaranteed to serve in at most one thread This was achieved through implementation of the SingleThreadModel interface This option is deprecated, since it may result in severe slowdown of performance -It is commonly recommended against…

69 Destroying Servlets The server may remove a loaded Servlet, Why?: -asked to do so by administrator(e.g. Server shutdown) -Servlet was idle a long time -server needs to free resources The server removes a Servlet only if all threads have finished or a grace period has passed Before removing, calls the destroy() method -can perform cleanup, e.g., close database connections Is it possible for the servlet to end without its destroy being called?

70 Example – Counting Threads public CountThreads extends HttpServlet { private int serviceCounter = 0;... //Access methods for serviceCounter protected synchronized void enteringServiceMethod() { serviceCounter++; } protected synchronized void leavingServiceMethod() { serviceCounter--; } protected synchronized int numServices() { return serviceCounter; }

71 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { enteringServiceMethod(); try { super.service(req, resp); } finally { leavingServiceMethod(); }

72 public ShutdownExample extends HttpServlet { private boolean shuttingDown; //Number of services, from before... //Access methods for shuttingDown protected void setShuttingDown(boolean flag) { shuttingDown = flag; } protected boolean isShuttingDown() { return shuttingDown; } Example – Clean Shutdown

73 public void destroy() { /* Check to see whether there are still * service methods running, * and if there are, tell them to stop. */ if (numServices() > 0) { setShuttingDown(true); } /* Wait for the service methods to stop. */ while(numServices() > 0) { try { Thread.sleep(interval); } catch (InterruptedException e) {} } }