1 CS6320 – Servlet Structure and Lifecycle L. Grewe.

Slides:



Advertisements
Similar presentations
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Advertisements

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.
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
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 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 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.
HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE.
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
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.
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.
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.
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Server-Side Software. Objective What is a servlet? Where do servlets fit in? What can servlets do? Why are servlets better than CGI? Servlet.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
1 Servlets Modified slides from Dr.Sagiv. 2 Introduction.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
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.
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.
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.
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.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Representation and Management of Data on the Web
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,
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.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Distributed Web Systems Java Servlets Lecturer Department University.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Servlets Hits Counter 20-Jul-18.
HTTP Servlet Overview Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might.
Chapter 26 Servlets.
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.
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.
Basic servlet structure
Presentation transcript:

1 CS6320 – Servlet Structure and Lifecycle L. Grewe

2 The Servlet Interface Java provides the interface Servlet Java provides the interface Servlet Specific Servlets implement this interface 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 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

3 Example – Generic Servlet import java.io.*; import java.servlet.*; public class HelloWorldServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException{ throws ServletException, IOException{ PrintStream out = newPrintStream(res.getOutputStream()); out.println("Hello world!"); } public String getServletInfo() { return "Hello World Servlet"; }}

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

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

6 Class HttpServlet Class HttpServlet handles requests and responses of HTTP protocol Class HttpServlet handles requests and responses of HTTP protocol The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: 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 This class is abstract

7 Creating a Servlet Extend the class HTTPServlet Extend the class HTTPServlet Implement doGet or doPost (or both) Implement doGet or doPost (or both) Both methods get: Both methods get: HttpServletRequest : methods for getting form (query) data, HTTP request headers, etc.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 clientHttpServletResponse : methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client Many times, we implement doPost by calling doGet, or vice-versa Many times, we implement doPost by calling doGet, or vice-versa

8 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"); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } HelloWorld.java

9 The Response: Returning HTML By default, no content type is given with a response By default, no content type is given with a response In order to generate HTML In order to generate HTML Tell the browser you are sending HTML, by setting the Content-Type headerTell the browser you are sending HTML, by setting the Content-Type header Modify the printed text to create a legal HTML pageModify the printed text to create a legal HTML page You should set all headers before writing the document content. Can you guess why? You should set all headers before writing the document content. Can you guess why?

10 public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(" Hello World \n"); out.println(" "); out.println(" " + new java.util.Date() + " \n"); out.println(" Hello World \n "); } } HelloWorld.java

11 Life of a Servlet  Birth: Create and initialize the servlet  Important method: init()  Life: Handle 0 or more client requests  Important methods: service(), doGet(), and doPost().  Death: Destroy the servlet  Important method: destroy()

12 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

13 The init() method  The init() method is called when the servlet is first requested by a browser request.  It is not called again for each request.  Used for one-time initialization. The method init is overloaded and has a parameter of type ServletConfig The method init is overloaded and has a parameter of type ServletConfig ServletConfig has methods to get external initialization parameters ServletConfig has methods to get external initialization parameters In Tomcat, these parameters are set in web.xmlIn Tomcat, these parameters are set in web.xml To make initializations, override init() and not init(ServletConfig) To make initializations, override init() and not init(ServletConfig) init() is automatically called by after performing default initializationsinit() is automatically called by after performing default initializations

14 Service() Method  Each time the server receives a request for a servlet, the server spawns a new thread and calls the servlet’s service () method. Browser Web Server Single Instance of Servlet service()

15 The Service Method  By default the service() method checks the HTTP Header.  Based on the header, service calls either doPost() or doGet().  doPost and doGet is where you put the majority of your code.  If your servlets needs to handle both get and post identically, have your doPost() method call doGet() or vice versa.

16 Thread Synchronization  By default, multiple threads are accessing the same servlet object at the same time.  You therefore need to be careful to synchronize access to shared data.  For example, the code on the next slide has a problem…

17 package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your ID"; String docType = … String id = "User-ID-" + nextID; out.println(" " + id + " "); nextID = nextID + 1; out.println(" "); } This code is problematic. Can result in a race condition, where two users can actually get the same User-ID! For example: User 1 makes request: String id = "User-ID-" + nextID; Gets nextId of 45. Now User 2 makes request, and pre-empts user 1: String id = "User-ID-" + nextID; Gets nextId of 45 (same one!) Admittedly, this case is rare, but it’s especially problematic. Imagine if user Id was tied to credit card number!

18 How to Solve Synchronization Problems  You have a few options for solving servlet synchronization issues: 1)Never use instance variables (or protect them) in your servlets…use local variables. If you don’t have shared instance variables, you don’t have shared synchronization problems. 2)Synchronize code explicitly with Java synchronization blocks. 3)Note recommended - Use the SingleThreadInterface

19 Java Synchronization  Use a synchronization block whenever accessing/modifying a shared variable.  For example: synchronized (this) { String id = "User-ID-" + nextID; out.println(" " + id + " "); nextID = nextID + 1; }

20 SingleThreadModel Interface  To prevent multi-threaded access, you can have your servlet implement the SingleThreadModel: public class YourServlet extends HttpServlet implements SingleThreadModel { …}  This will guarantee that your servlet will only process one browser request at a time.  It therefore addresses most synchronization issues.  Unfortunately, however, it can result in severe slowing of performance, and most people strongly recommend against using it.  In fact, the SingleThreadModel interface is now deprecated in the Servlet 2.4 API.

21 Death of a Servlet  Before a server shuts down, it will call the servlet’s destroy() method.  You can handle any servlet clean up here. For example:  Updating log files.  Closing database connections.  Closing any socket connections. The server may remove a loaded Servlet, Why?: The server may remove a loaded Servlet, Why?: asked to do so by administrator(e.g. Server shutdown)asked to do so by administrator(e.g. Server shutdown) Servlet was idle a long timeServlet was idle a long time server needs to free resourcesserver needs to free resources The server removes a Servlet only if all threads have finished or a grace period has passed The server removes a Servlet only if all threads have finished or a grace period has passed

22 Example: Persistent Counter  To create a persistent record, we can store the count value within a “counter.txt” file.  init(): Upon start-up, read in the current counter value from counter.txt.  destroy(): Upon destruction, write out the new counter value to counter.txt

23 import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterPersist extends HttpServlet { String fileName = "counter.txt"; int count; public void init () { try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial); } catch (FileNotFoundException e) { count = 0; } catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; } } At Start-up, load the counter from file. In the event of any exception, initialize count to 0. Continued….

24 // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); count++; out.println ("Since loading, this servlet has " +"been accessed "+ count + " times."); out.close(); } Each time the doGet() method is called, increment the count variable. Continued….

25 // At Shutdown, store counter back to file public void destroy() { try { FileWriter fileWriter = new FileWriter (fileName); String countStr = Integer.toString (count); fileWriter.write (countStr); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } When destroy() is called, store new counter variable back to counter.txt. Any problems with this code?