HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE.

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.
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
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 and a little bit of Web Services Russell Beale.
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.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
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 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. 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, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
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.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
Objectives Java Servlet Web Components
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.
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.
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 6 Server-side Programming: Java Servlets
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.
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
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.
SE-2840 Dr. Mark L. Hornick1 Servlet Threads and Sessions.
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.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
©SoftMooreSlide 1 Session Tracking with Servlets.
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,
Introduction To HTML Dr. Magdi AMER. HTML elements.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
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.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Servlet API and Lifecycle
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.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE

HTTP Requests, continued URI (required in HTTP/1.1) Header Fields E.g. how the response should be returned, under what conditions, identification and characterization of client, accounting data Body POST data Empty for GET

HTTP Response: Status code (machine), reason (human) Header Metadata, e.g. Content-Type (Media type), Content-Length, Last-Modified, Etag Body (X)HTML, other XML, text, binary data …

URL Connections java.net also -- connections extend Socket Encapsulates HTTP and FTP connections URI, URL, URLConnection, HttpURLConnection

Servlets Definition Server side component in a client server model (now the browser is the client ) Reside in a servlet container, assigned to a certain URL pattern. Provide mechanisms for maintaining state over the stateless HTTP protocol

Servlet Model

Servlet API Interfaces: HttpServletRequest HttpServletResponse HttpSession HttpBindingSession HttpSessionContext Interfaces are implemented by server providers and can be used out of the box

Servlet API Classes Cookie HttpServlet HttpSessionBindingEvent HttpUtils

Servlet Lifecycle

Multithreaded access (usually default) init called first time only (by the container) zero to many calls to service destroy called

init (ServletConfig) call super.init (config), or just use init () Called once Prior to any call to service Don’t worry about multithreading issues here Sometimes used to get resources needed for the lifetime of the servlet

service (req, resp) Not usually overridden Default impl. determines what request handler to call (based on HTTP request type), calls it Service method will call doGet, doPost, doPut, etc. based on service type. Default implementations provided for doHead, doTrace, doOptions

doPost, doGet, etc. doPost (HttpServletRequest req, HttpServletResponse resp) Implement this to handle POSTs Read from req, build resp Multithreaded access by default (depending on server config) Beware instance variables, shared data config and context are shared, session is usually safe, req / resp are not Use locks and/or synchronized data structures if shared data is an issue

destroy () called once Servlet timeout, servlet reload, container shutdown Other threads may still be processing service requests, no further requests will be processed Release resources, write data, etc.

Servlet Skeleton import javax.servlet.* import javax.servlet.http.* import java.io.* public class myServlet extends HttpServlet { void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType (“text/html”); PrintWriter out =response.getWriter();. out.close() }

Generating output, handling form data, maintaining state

Servlet API Main Roles Servlet Class for handling client request HttpServletRequest for getting all the information that the client passed HttpServletResponse for sending a response to the client Cookie/Session for storing and reading session variables

Review Typically used in HTTP servers Server side of HTTP request/response Interpret request, generate response Servlets are container-managed Respond to events, doXXXX Need to consider lifecycle, threading policies, security, resource access and configuration

Generating (X)HTML Set content type Access response output stream As a PrintWriter, via response.getWriter () Use out.println, out.print Escape quotes You are responsible for all content, including doctype header (and xml declaration if using XHTML)

HTML Forms Form data consists of name, value pairs Values are retrieved on the server by name GET passes data in the query string Always URL-encoded POST passes data in content of request Either URL-encoded, or multipart/form-data

Structure of forms form element Attributes: action (REQUIRED) method (GET) enctype, accept, accept-charset onsubmit, onreset

Forms contain controls input : many kinds of form data Text fields, checkboxes, radio buttons, passwords, buttons, hidden controls, file selectors, object controls button : type=submit|button|reset select : a menu, contains option child elements textarea : multi-line text input field Other html tags can be present (e.g. format forms in tables)

Servlet support Does decoding for you, common interface Just use request.getParameter (String name) for both GET and POST Returns null if parameter doesn’t exist Multipart not well supported in standard API Use request.getReader (), request.getInputStream ()..parse yourself Use 3rd party API, e.g. com.oreilly.servlet.multipart.MultipartParser, org.apache.commons.fileupload.servlet

More Servlet Support Retrieve all values matching name: request.getParameterValues (String name) Returns String array, or null Retrieve all parameter names: request.getParameterNames () Returns String Enumeration Retrieve an immutable Map of name, value pairs request.getParameterMap ()

Maintaining State Cookies Name,value pairs with properties Lifetime independent of request/response Passed between client and server during HTTP transactions Hidden fields, URL rewriting Form controls (input type=“hidden”) added dynamically to pages, containing name/value that should be associated with client. Hardcoded links (href) contain name/value data in query

Maintaining State, continued Sessions Pass a single cookie (or fallback to URL rewriting) containing a session ID Server maintains a mapping between session ID and associated data stored on the server

Cookie Support Cookie class Cookie Name, value Domain, path maxAge > 0 Persist cookie, in seconds -1 (default) in memory, until browser is closed 0 delete cookie on client

Using Cookies Retrieving cookies request.getCookies () returns array of Cookie or null Creating cookies Cookie (String name, String value) Updating client Existing Cookies can be modified, but must be added to response for change to take place response.addCookie (Cookie c)

Sessions Support in Java HttpSession is an interface for a glorified (specialized) Map or similar One-to-one mapping between jsessionID and HttpSession Attached to HTTPServletRequest object in doXXXX methods request.getSession (boolean create=true) request.isRequestedSessionIdValid ()

Sessions support Associated with one client (usually) Id, creation time, last accessed time Can be invalidated manually or due to inactivity Lifetime: new-->active-->invalid Object getAttribute (String name) setAttribute (String name, Object o) Enumeration getAttributeNames ()

More Session details Interface maps String to Object, you must cast ref to derived type If your object uses generics (e.g. typed lists), you’ll get a compiler warning when casting Interface is pre 1.5, strips away type info Any other code can take e.g. a List session object and treat it as an untyped list Solutions: be careful, store keys into external structures, use Checked wrappers on collections (runtime cost)

ServletConfig Provided to a servlet upon initialization by the web server (container) Simple read only interface to configuration details String getInitParameter (String name) Enumeration getInitParameterNames () String getServletName () Can also access ServletContext

ServletContext Lets a servlet communicate with its container Access container-managed resources, dispatch requests, write to logs Can be used as a global data store (like an application-wide session) But is specific to single web container -- does not work in clustered scenarios Recommendation is to use a resource that is shared (e.g. cached DataSource, directory) We will see/use the servlet context later on

Questions?