Robinson_CIS285Winter2005 Servlets CIS 285 25 January 2005 Mary Robinson.

Slides:



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

 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Technology Overview JAVA Servlets CS-611 S. Witherspoon.
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.
HTTP – HyperText Transfer Protocol
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
CS320 Web and Internet Programming Generating HTTP Responses
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
HTTP Hypertext Transfer Protocol. HTTP messages HTTP is the language that web clients and web servers use to talk to each other –HTTP is largely “under.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
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.
Session-02.
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.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
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.
Web technologies and programming cse hypermedia and multimedia technology Fanis Tsandilas April 3, 2007.
CP476 Internet Computing Lecture 5 : HTTP, WWW and URL 1 Lecture 5. WWW, HTTP and URL Objective: to review the concepts of WWW to understand how HTTP works.
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.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
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.
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.
Chapter 6 Server-side Programming: Java Servlets
WWW: an Internet application Bill Chu. © Bei-Tseng Chu Aug 2000 WWW Web and HTTP WWW web is an interconnected information servers each server maintains.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
Copyright © 2002 ProsoftTraining. All rights reserved. Java Servlets.
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
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.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Overview of Servlets and JSP
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
JAVA, JEE Training Introduction to Web Harinath Mallepally
Java Servlets References: Karen Anewalt, Mary Washington College.
CS122B: Projects in Databases and Web Applications Spring 2017
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Web Development Web Servers.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre-assessment Questions
Servlet API and Lifecycle
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.
Objectives In this lesson you will learn about: Need for servlets
J2EE Lecture 1:Servlet and JSP
Presentation transcript:

Robinson_CIS285Winter2005 Servlets CIS January 2005 Mary Robinson

Robinson_CIS285Winter2005 What is a Servlet Pure Java alternative to CGI Java technology that runs in the server tier Dynamic Exists in the “layer” between browser and database applications

Robinson_CIS285Winter2005 Servlets A web component written in java, whose purpose is the generation of dynamic content Its execution and lifecycle are managed by a Web container within an application server. Can interact with Web clients indirectly via the container, using HTTP request-response protocol. Client, via web browser, can invoke a servlet: Entering a URL in the browser Clicking a hypertext link Submitting an HTML form

Robinson_CIS285Winter2005 How Do I Run Servlets ? Need a Web container (servlet container is no longer required Tomcat (Apache), WebSphere, BEA Web Logic, JRUN Some servlet reference implementations are still free Can be run standalone Can be integrated with Web server: Apache IIS, IES(nee NES) and so forth

Robinson_CIS285Winter2005 Why Use Servlets? Easier to program Servlets all share the same structure and basic method calls – easier to code Servlet classes provide parsing and decoding of input data Support for session tracking Support for cookies Little training is required to write servlets. J2EE compliant – just need to follow the J2EE specifications and servlets should run correctly.

Robinson_CIS285Winter2005 Why Use Servlets? Better use of system resources CGI starts a new process for each HTTP request For each Java Servlet, each new request for a specific servlet starts a new thread of execution Java Portability Write once, run anywhere Supported by many application servers Part of Java 2 Platform (J2EE)

Robinson_CIS285Winter2005 Why Use Servlets? Type checking Java is a typed language Exception handling allows for robust error handling JVM protect the system from Java coding issues For each Java Servlet, each new request for a specific servlet starts a new thread of execution Security Runs in the Web container Can restrict servlet access Can be part of a Single (global) Sign On security architecture.

Robinson_CIS285Winter2005 Using Servlets Servlets extend function of server to include server-side programming as a java class. May do anything the Web server cannot inherently do: Query a database Perform calculations such as tax on purchases Servlets are portable and runtime environment is standardized, therefore the application server’s handling of requests is also standardized.

Robinson_CIS285Winter2005 HTTP Transaction HTTP is a protocol that allows Web browsers to talk to servers and exchange information HTTP provides a standard way of communicating between browsers and servers HTTP expects the client to initiate a request and the server to respond.

Robinson_CIS285Winter2005 HTTP Flows: Forms / POST Request GET (request) HTML document RequestParamExample.html Return (response) document Submit form (POST action) (request) Server returns the HTML document Generated by the java servlet – based on the input from the form (response) Client / Browser Web Server / Application Server

Robinson_CIS285Winter2005 Initiating an HTTP Response Request line. This line contains a request method, the document location, and the protocol version. Header section. This series of lines contains HTTP headers that are used to pass other information about the request, and about the client itself, to the server. A blank line then separates the header section from the entity body. Entity body. This section contains other data to be passed to the server. There is usually information here only when a form is submitted.

Robinson_CIS285Winter2005 Transaction Example If we typed the URL into Netscape: The browser would issue an HTTP request similar to the following: GET /simple.html HTTP/1.0 User-Agent: Mozilla/4.5 [en] (X11; SunOS sun4m) Accept: image/gif, image/x-xbitmap, image/jpeg, */*

Robinson_CIS285Winter2005 Transaction Example The server then responds to the request in a similar fashion: Status line. This line contains the protocol version, a status code, and a reason phrase. Header section. This series of lines contains HTTP headers that are used to pass other information about the response, and about the server itself, to the client. A blank line then separates the header section from the entity body. Entity body. This section, if present, contains the document (or object) requested.

Robinson_CIS285Winter2005 Server Response May Look Like This: HTTP/ OK Date: Mon, 24 Jan :33:10 GMT Server Apache/1.3.1 (Unix) Last-Modified: Tue, 20 Dec :00:15 GMT Content-Length: 49 Content-Type: text/html Welcome to the webmaster server…

Robinson_CIS285Winter2005 Request Methods Request line of a client request that contains an HTTP command called a request method Defines what server does with the request Currently several methods are defined by HTTP 1.1 standard Only a few are widely supported by HTTP servers

Robinson_CIS285Winter2005 Methods HEAD Method The HEAD method is identical to the GET method except that the server does not return a document; it returns only the header section for the request. The HEAD method is useful for verifying that a document exists for checking links or to get information about the file type and modification time only. POST Method The POST method allows the server to receive data from the client. It is most commonly used to send the data in HTML forms to the server for processing. This method passes data to the server in the entity body of the request.

Robinson_CIS285Winter2005 Other Methods PUT method is becoming more widely supported. It is used for publishing documents to the Web server from a client. Many of the latest HTML authoring packages support posting documents to a Web server via the PUT method. DELETE method is used to remove a document from a Web server.

Robinson_CIS285Winter2005 Server Response 1. Informational. The request was received and is being processed. 2. Success. The client request was successful. 3. Redirection. The client request was not performed; further action must be taken by the client. 4. Client error. The client’s request was incomplete or incorrect and cannot be fulfilled. 5. Server error. The request was not fulfilled, due to a server problem

Robinson_CIS285Winter2005 Server Response Informational 1XX 100 Continue Success 2XX 200 OK Redirection 3XX 301 Moved permanently 302 Found (Moved Temporarily 304 Not Modified Client error 4XX 400 Bad Request 403 Forbidden 404 Not Found Server error 5XX 500 Internal Server Error

Robinson_CIS285Winter2005 HTTP Flows: Forms / POST Request GET (request) HTML document RequestParamExample.html Return (response) document Submit form (POST action) (request) Server returns the HTML document Generated by the java servlet – based on the input from the form (response) Client / Browser Web Server / Application Server

Robinson_CIS285Winter2005 HTTP Flows - HTML

Robinson_CIS285Winter2005 HTTP Protocol Request Conversation between a browser and a server Request phase Request (POST in this example) Header values A blank line Posted data (when request method is POST)

Robinson_CIS285Winter2005 HTTP Protocol Request POST /example/servlets/RequestParamExample HTTP 1.0 Referrer: Connection: Keep-Alive User-Agent: Mozilla/4.72 [en (WinNT 5.0; U)] Host: localhost:8080 Cookie: USERID=spot Accept: image/gif, image/x-xbitmap, image/jpeg, */* Accept-Language: en Accept-Charset: iso ,*,utf-8 Content-type: application/x-www-form-urlencoded Content-length: 80

Robinson_CIS285Winter2005 HTTP Protocol - Response Response phase Status information (200 in example) Header values A blank line Output document (HTML)

Robinson_CIS285Winter2005 HTTP Protocol - Request HTTP/ ok Content-Type: text/html Set-Cookie: sessionid=5H2HXGYAAAAEWAAAAZJCI;Path=/ Cache-Control: no-cache=“set-cookie,setcookie2” Expires: Thu, 26 Dec :00:00 GMT Set-Cookie: USERID=spot; Expires=Fri, 24-Jul :30:37 GMT Accept: image/gif, image/x-xbitmap, image/jpeg, */* Content-Language: en Mary Robinson

Robinson_CIS285Winter2005 Servlet Process Flow Client makes a request naming a servlet as part of the URL Web server forward request to Servlet engine (Web container Servlet engine locates instance of a Servlet class Servlet engine calls Servlet’s service method Servlet builds response dynamically and passes it to Web server Web server sends the response back to the client

Robinson_CIS285Winter2005 Servlet Process Flow Browser (client) Web Server Application Server Servlet Instance URL request response

Robinson_CIS285Winter2005 What is a Servlet ? Servlets, as the name implies, are service requests The servlet API is a set of java classes which define a standard interface between a Web client and a Web server Servlet API includes two packages javax.servlet* javax.servlet.http*

Robinson_CIS285Winter2005 Java Servlet API The servlet API is a set of Java classes that implement one of the interfaces defined in the javax.servlet* or javax.servlet.http* javax.servlet.Servlet javax.servlet.GenericServlet javax.servlet.http.HttpServlet Implements

Robinson_CIS285Winter2005 Servlet Process Servlets are deployed or loaded into a servlet container The container invokes method callbacks On servlets methods during different stages of its lifecycle When a client requests service

Robinson_CIS285Winter2005 Process Flow Client (Web browser) initiates call to the servlet Web browser sends HTTP request to Web server Web server determines content – dynamic for a servlet Web server forward request to application server, again using HTTP, to an embedded HTTP server

Robinson_CIS285Winter2005 Process Flow Continued The Web container within the application server handles communication with the servlet, passing the request and response as objects Servlet is Java code with standard Java interfaces. Example: Servlet may collaborate with other classes and objects to accomplish work such as database queries Servlet has answer for client and formats the answer in HTML dynamically Directly Indirectly – JSP’s

Robinson_CIS285Winter2005 Java Servlet Lifecycle Methods Individual servlet lifecycle Create Initialize Available For service Servicing requests Unavailable For service Destroy Unload

Robinson_CIS285Winter2005 Servlet Lifecycle Methods Basic interface, javax.servlet.Servlet, defines a set of five methods that have to be implemented to provide a service and for the lifecycle methods init service doGet doPost destroy Individual servlet lifecycle

Robinson_CIS285Winter2005 Servlet Lifecycle The lifecycle of a servlet is expressed in the Java servlet API: in the init service (doGet or doPost) destroy methods of the Servlet interface.

Robinson_CIS285Winter2005 Life Cycle Web server passes request to application server Application server uses a JVM to execute the servlet JVM allows a servlet to handle multiple requests simultaneously on separate lightweight threads of execution Over head of loading and starting servlet is significantly reduced to one occurrence Application server keeps servlet in memory waiting for another request.

Robinson_CIS285Winter2005 Java Servlet Lifecycle Create Initialize Available For service Servicing requests Unavailable For service Destroy Unload (Unavailable Exception thrown) (Initialize failed)

Robinson_CIS285Winter2005 Servlet Creation Servlets are loaded and instantiated When the container is started When the container determines the servlets are needed to service requests(first requests)

Robinson_CIS285Winter2005 Servlet Initialization Before servlet can handle requests from clients Perform one-time activities and initialize costly resources Init() method performs servlet initialization such as loading default data parameters Two init() methods One takes no input parameters Other takes a ServletConfig reference as a parameter

Robinson_CIS285Winter2005 Servlet Request Handling Accept client requests and send responses back via the Web server. Service(), doGet(), doPost()..methods are called in response to clients (each HTTP request is on a different thread). Default service() method calls the doGet() method whenever an HTTP GET request is sent by the Web client (usually a URL). The doPost() method is called whenever an HTTP POST request is sent by the Web browser client(usually action in HTML form).

Robinson_CIS285Winter2005 Java Servlet API The servlet API is a set of Java classes that implement one of the interfaces defined in the javax.servlet* or javax.servlet.http* javax.servlet.Servlet javax.servlet.GenericServlet javax.servlet.http.HttpServlet Implements

Robinson_CIS285Winter2005 Servlets and HTTP Most servlets are used in a Web environment where HTTP is used between a Web client (browser) and the Web server/application server Much of the standard processing must take place in this HTTP-based environment is managed by javax.servlet.http.HttpServlet Typical servlet will extend this class and override one or more of the standard methods Ex. doGet() or doPost() to supply specific servlet behavior

Robinson_CIS285Winter2005 ServletConfig & Initialization Parameters The ServletConfig is used by the servlet container to pass information to the servlet during initialization Accessed via the GenericServlet method getServletConfig() ServletConfig: Contains initialization parameters as a set of name/value pairs. public String getInitParameter (String name) public Enumeration getInitParameterNames() Maintains a reference to the servletContext object which gives the servlet information about the serve Public ServletContext getServletContext()

Robinson_CIS285Winter2005 Servlet Definition web.xml File RegistrationServlet com.ibm.ils.exam.servlet.RegistrationServlet MaxTries 4 MaxTries 4 1 RegistrationServlet Register

Robinson_CIS285Winter2005 Example Servlet: With Init Parameters // servlets init method public void init() { String maxTries; string autoSave; maxTries = getInitParameter(“MaxTries”); autoSave = getInitParameter(“AutoSave”); // process the parameters …. }

Robinson_CIS285Winter2005 Example Servlet: With Init Parameters // servlets init method public void init() { ServletConfig config = getServletConfig(); String maxTries; string autoSave; maxTries = config.getInitParameter(“MaxTries”); autoSave = config.getInitParameter(“AutoSave”); // process the parameters …. }

Robinson_CIS285Winter2005 HTTPServlet An HTTP-specific request handler Adds HTTP specific methods doGet() – handle a GET request (URL) doPost() – handle a POST request(HTML form) Subclasses override the doGET, doPost, and so forth, methods and may override init() and destroy() doGet() and doPost() do the work and are called by service()

Robinson_CIS285Winter2005 Requests and Responses The service(), doGet() and doPost() methods each have two parameters: HttpServletRequest – provides access to request data (parameters), HttpSession information, and so forth. HttpServletResponse – provides services to allow the servlet to supply a response to the requesting client. Most servlet programming involves reading a request and writing a response.

Robinson_CIS285Winter2005 HttpServlet Request Represents client’s request Getters for aspects of request, for example: Request header, content type, length, method Request URL as a String and request servlet “path” Client security type Access request parameters by name Possible scope for object sharing among participants satisfying the request

Robinson_CIS285Winter2005 Request Protocol The request object encapsulates all information from the client request. The following methods are available to access parameters: getParameterNames() Returns an enumeration of parameters on the HTML page getParameterValues(String name) Returns the value of a multivalued parameter getParameter(String name) Returns the value of a specific named parameter getReader() Returns a BufferedReader to view input

Robinson_CIS285Winter2005 HttpServletResponse Represents communication channel back to client Sets the content type and status code Sets content headers (cookies, caching, and so forth) Allows servlet to return dynamic content or error information Redirects client to another URL

Robinson_CIS285Winter2005 Response Protocol setContentType(String type) Set the content type for this response Type is a MIME type getWriter() Returns a reference to the PrintWriter getOutputStream() Returns a reference to the ServletOutputStream Used to create binary documents

Robinson_CIS285Winter2005 Single-Threaded Servlets By default servlets must support multiple threads of execution Servlets can be forced to be single- threaded if they implement the SingleThreadModel interface. The application server guarantees that no more than one request thread will simultaneously access an instance of a servlet

Robinson_CIS285Winter2005 Single-Threaded Servlets Any single-threaded servlet can be considered thread safe and is not required to synchronize access to its instance variable, but the ruled must be followed: Must still carefully manage any non-final instance and class fields Shared memory and resources must be locked Possible needs for synchronized methods Usually performs poorly and should be avoided.

Robinson_CIS285Winter2005 Java Servlet Extends javax.servlet.http.HttpServlet Override the doGet or doPost methods to process HTTP GET or POST requests Process HttpServletRequest input values Invoke the business process Set the HttpServlet Response values Output HTML to the output PrintWriter- Servlets are inherently multithreaded

Robinson_CIS285Winter2005 MVC: Model, View, Controller Blatantly “borrowed” from Model 1 Model 2

Robinson_CIS285Winter2005 Servlet Architecture Geared towards one goal: PERFORMANCE