Core Servlets Chapter 3 Link for Core Servlets code:http://volume1.coreservlets.c om/archive/http://volume1.coreservlets.c om/archive/

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.
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.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
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 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
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.
Java Servlets and JSP.
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.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
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.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
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.
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.
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.
Java Servlets and Java Server Pages Norman White Stern School of Business.
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.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
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.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Configuration Web Server Tomcat - Install JDK Install Tom cat Configure Tom cat for running Servlet C:\Program Files\Apache Software Foundation\Tomcat.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Chapter 4 Request and Response. Servlets are controlled by the container.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Distributed Web Systems Java Servlets Lecturer Department University.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Servlets Hits Counter 20-Jul-18.
Chapter 26 Servlets.
CS3220 Web and Internet Programming Introduction to Java Servlets
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.
Basic servlet structure
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/

The purpose of servlets Servlets are a middle layer between the client and applications on the HTTP server like database access, legacy applications, java programs, and web services. In Java, these applications have names like JDBC, JNI, RMI, and SOAP.

Steps or phases 1.Read explicit data from client: The end user enters data, usually in an HTML form. Data could also come from an applet or custom HTTP program. 2.Read the implicit HTTP request data sent by the browser. This includes cookies, media types and compression schemes the browser can handle. 3.Generate the result. This may mean talk to a database, execute an RMI or CORBA call, invoke a web service, etc. and then to embed the results into a document. 4.Send the explicit data to the client. This may be text, XML, HTML, binary and so on. 5.Send the implicit HTTP response data. This includes information on the type of document being returned, setting cookies, caching parameters and so on.

Servlet Structure import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //use request object to read HTTP headers, cookies, query string //use response object to specify HTTP response status code and headers // (eg., content type, cookies…) … PrintWriter out = response.getWriter(); //use out to send content to the browser }

HttpServletRequest and HttpServletResponse Servlets usually – not always – extend HttpServlet and override doGet and doPost methods of that class. Each takes two arguments, an HttpServletRequest and HttpServletResponse. Incoming data, like query string, headers and client hostname, is in the request. Status codes, respnse headers, and document content are sent back via the response.

Generating html Generally, most of your energy in generating a response is used in writing html via a printwriter.

packaging If packages are used, servlets must be placed in subdirectories matching the package name. Package statement must appear first in the servlet code. The lottery number generator servlet from chapter 3 has examples of generating html and using a package. This servlet would need to be placed in a coreservlets subdirectory of classes, as in: C:\tomcat\webapps\ROOT\WEB-INF\classes\coreservlets The text recommends using an html validator to check the synatx of generated pages. WWW has one at Text suggests cutting down page generation tedium by using utilities. Typically, if most of what you are doing is html generation, you would look elsewhere for your middle-tier solution, like at JSP.

Life cycle init() is called on servlet instantiation – put one- time setup code here. Afterwards, each user request causes a thread to be started which calls the service method of this servlet. If multiple calls occur, multiple threads are created, unless you have stipulated that the SingleThreadModel is to be used. Before termination, the server calls the servlet’s destroy method.

Service method Service method checks the request type (Get, Post, XXX) and calls doGet, doPost or doXXX appropriately. Get occurs from a URL page request or any HTML form with no method specified. Text advises not to override service method. Instead, if the servlet does the same thing for get and post and needs to provide both, doGet might be written and the doPost method simply calls doGet: public void doPost(…)…{ //just call doGet doGet(…);}

More about init() Init typically initializes data that will be used throughout the life of the servlet. This might include time-consuming operations that only need to be done once. This might mean setting up a pool of db connections or a building a hashmap from a datafile. The lottery number example builds an array of numbers in init – these will remain the same until the server is shutdown or servlet is destroyed. It also stores the time in a variable modTime, in case a get request only wants the numbers if modified after a specified time.

Most of LotteryNumbers…see notes for entire servlet package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LotteryNumbers extends HttpServlet { private long modTime; private int[] numbers = new int[10]; public void init() throws ServletException { // Round to nearest second (i.e, 1000 milliseconds) modTime = System.currentTimeMillis()/1000*1000; for(int i=0; i<numbers.length; i++) { numbers[i] = randomNum(); } } /** Return the list of numbers that init computed. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your Lottery Numbers"; String docType = " \n"; out.println(docType + " \n" + " " + title + " \n" + " \n" + " " + title + " \n" + " Based upon extensive research of … best lottery numbers for you. " + " "); for(int i=0; i<numbers.length; i++) { out.println(" " + numbers[i]); } out.println(" " + " "); } … }

Lottery Numbers

Initializations controlled by parameters Initialization parameters can also be used to set values when a servlet is loaded. These typically are used by deployers – they would enable the address of a database, the size of a connection pool or location of a file to be gleaned at startup from data in web.xml See Hunter chapter 3 notes for an example.

destroy() Use this to close db connections, write data to disk, close threads. Since the server may crash, do not rely on destroy being run.

SingleThreadModel Implementing this interface means you don’t have to worry about simultaneous access to instance variables, since only a single user (thread) can be executing at once, (or a pool of multiple instances). You do have to worry about access to static fields or shared data outside the servlet. SingleThreadModel hurts performance, and may not effectively synchronize access, so it should generally not be used. Instead synchronize sections of code where exclusion is needed.

Example – assign a unique user id. Hunter has examples illustrating this problem, too, so I don’t include a discussion of the problems here. The servlet is given and the “code fix” follows.

Generate unique user ids 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 = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + " \n" + " " + title + " \n" + " \n" + " " + title + " \n"); String id = "User-ID-" + nextID;////notice not synched out.println(" " + id + " "); nextID = nextID + 1; out.println(" "); }

Properly synchronized synchronized(this){ //an unnamed synch block String id = "User-ID-" + nextID; out.println(" " + id + " "); nextID = nextID + 1; }

UserIDs

debugging Use print statements Use an integrated debugger in the IDE. JBuilder, Eclipse and many IDEs let you insert breakpoints, trace method calls, etc. Use the log file. HTTPServlet class has a log method that lets you write to a file on the server. Use Log4J, part of the Apache project. It lets you insert debug statements and use an XML config file to determine which are invoked at request time. Write separate classes. As usual, decomposition and class cooperation can help isolate if not eliminate errors. Check for malformed or missing data. Check the html source by using the browsers “view source” to find html errors. L\Examine request data separately… The Core Servlets text provides an EchoServer class to do this. Look at the response separately. The WebClient class in Core Servlets text chapt 3 lets you connect ot the server, send HTTP data and view everything returned. Stop and restart the server. If you change a lower-level class, even if your container is set to reload your servlets when updated, maybe the change won’t be implemented.

WebClient This is a standalone application (not a servlet!) that can be used to interactively connect to servers and test servlets, JSP pages, etc. Download all the files, compile it with "javac WebClient.java" (which will compile all the auxiliary files). Then, run it from the command line with "java WebClient", and type in the host, URI, HTTP headers, etc.

Running the Web Client