China Jiliang University Java. Web Programming in Java. Java Servlet Programming. Java Web Applications, Helmut Dispert

Similar documents
Servlet Fudamentals. Celsina Bignoli

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Java Servlets. Preparing your System

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Session 8. Introduction to Servlets. Semester Project

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Servlets and JSP (Java Server Pages)

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Advanced Web Technology

SERVLETS INTERVIEW QUESTIONS

UNIT-V. Web Servers: Tomcat Server Installation:

JAVA SERVLET. Server-side Programming INTRODUCTION

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Servlets Basic Operations

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Session 9. Introduction to Servlets. Lecture Objectives

Module 4: SERVLET and JSP

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

Web based Applications, Tomcat and Servlets - Lab 3 -

Servlet Basics. Agenda

JSP. Common patterns

HTTP and the Dynamic Web

Questions and Answers

Advanced Internet Technology Lab # 4 Servlets

Servlets. An extension of a web server runs inside a servlet container

SSC - Web applications and development Introduction and Java Servlet (I)

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

Chapter 10 Web-based Information Systems

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

AJP. CHAPTER 5: SERVLET -20 marks

The Structure and Components of

CIS 455 / 555: Internet and Web Systems

Unit 4 - Servlet. Servlet. Advantage of Servlet

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Using Java servlets to generate dynamic WAP content

Oracle Containers for J2EE

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Table of Contents. Introduction... xxi

Introduction to JSP and Servlets Training 5-days

Handling the Client Request: HTTP Request Headers

Java4570: Session Tracking using Cookies *

Lecture 3. HTTP v1.0 application layer protocol. into details. HTTP 1.0: RFC 1945, T. Berners-Lee HTTP 1.1: RFC 2068, 2616

The Servlet Life Cycle

Chapter 29 Servlets: Bonus for Java Developers 1041

Public Draft. Java Servlet Specification v2.3 PUBLIC REVIEW DRAFT 1 PUBLIC REVIEW DRAFT 1

Web Based Solutions. Gerry Seidman. IAM Consulting

Java Servlet Specification, v2.2

Java Servlet Specification Version 2.3

ServletConfig Interface

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Java E-Commerce Martin Cooke,

Application Servers in E-Commerce Applications

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

CSC309: Introduction to Web Programming. Lecture 8

Chapter 10 Servlets and Java Server Pages

Handout 31 Web Design & Development

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Unit 5 JSP (Java Server Pages)

Introdução a Servlets

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

SERVLET AND JSP FILTERS

CS506 Web Design & Development Final Term Solved MCQs with Reference

Fast Track to Java EE

Servlets Pearson Education, Inc. All rights reserved.

********************************************************************

LearningPatterns, Inc. Courseware Student Guide

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Introduction. This course Software Architecture with Java will discuss the following topics:

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Problems in Scaling an Application Client

JAVA SERVLETS INTRODUCTION SERVLETS SHRI GURU RAM RAI INSTITUTE OF TECHNOLOGY & SCIENCE, DEHRADUN

COMP9321 Web Application Engineering

Deccansoft Software Services. J2EE Syllabus

Introduction to Web applications with Java Technology 3- Servlets

13. Databases on the Web

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

web.xml Deployment Descriptor Elements

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Java Card 3 Platform. Peter Allenbach Sun Microsystems, Inc.

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

Advanced Java Programming

Unit-4: Servlet Sessions:

Distributed Systems 1

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

index_ qxd 7/18/02 11:48 AM Page 259 Index

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Transcription:

Java Web Programming in Java Java Servlet Programming

Java 2 Platform Editions JavaCard Java Technology Enabled Devices Java Technology Enabled Desktop Workgroup Server High-End Server Micro Edition Standard Edition Enterprise Edition

Java 2 Platform Profile Profile Profile Profile Java Java 2 Enterprise Edition (J2EE) Core Core APIs APIs Profile Profile Profile Profile Java Java 2 Standard Edition (J2SE) Core Core APIs APIs Java 2 Platform, Micro Edition (J2ME) encompasses VMs and core APIs specified via Configurations as well as vertical or market-specific APIs specified in Profiles. TV TV Screen Screen Car Profile Profile Phone Phone Profile Car Profile Profile Profile Personal Personal Profile Profile Mobile Information Mobile Device Information Profile Device Profile Java Java 22 Micro Micro Edition Edition Core Core APIs APIs Smart Card Smart Profile Card Profile Java Java Programming Language Java Java HotSpot HotSpot Java Java Virtual Virtual Maschine Maschine (JVM) (JVM) KVM KVM Card Card VM VM

Java Technology / Range of Devices

J2EE Platform Tools Application Programming Model Applets Applets JavaBeans JavaBeans EJBs EJBs JSPs JSPs Container CORBA CORBA Servlets Servlets Transactions Messaging Mail Java 2 SDK, Standard Edition RMI RMI Database Database Naming Naming // Directory Directory Connectors

JAVA 2 EE Standard platform for web applications J2EE platform released December 1999. HTML presentation APIs Servlet 2.2 JavaServer Pages 1.1 2008: Servlet 2.5 and JSP 2.1 specifications Many other subsystems standardized under a single platform EJB and JDBC technologies JTA, JTS, JMS, JavaMail API, RMI-IIOP RMI: Remote Method Invocation, JTA: Java Transaction API IIOP: Internet Inter-Orb Protocol, JTS: Java Transaction Service API JMS: Java Message Service API

Jakarta - Tomcat Jakarta Project The goal of the Jakarta Project is to provide commercialquality server solutions based on the Java Platform that are developed in an open and cooperative fashion. Jakarta is the "overall" project for many subprojects. For example, Tomcat is the Servlet+JSP Engine which is a subproject of the Jakarta Project.

Jakarta - Tomcat 21 December 2011 - Jakarta Retired Jakarta Tomcat Tomcat is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process. Tomcat is developed in an open and participatory environment and released under the Apache Software License.

Standard Services and APIs Presentation Business Logic Data Access Servlet Java Server Pages EJB JDBC Client Data JTS/JTA JNDI JavaMail RMI-IIOP JMS Java 2 Enterprise Edition APIs

What Are Servlets? Java technology objects which extend the functionality of an HTTP Server. Comparable to Netscape s NSAPI, Microsoft s ISAPI, or Apache Modules Platform Independent Server Independent

What Are Servlets? Multiple requests In a single session Web Server Servlet Engine Container Request Response URL1 Servlet 1 Browser Request Response URL2 Servlet 2

Servlets Servlets run inside a JVM on the server Requests are handled by separate Threads within the web server process. Servlets can interact very closely with the server. Servlets can provide thin-client connectivity to a large enterprise application. Since servlets reside on the server, they can act as a middleware gateway to legacy systems. Servlets can provide controlled access to a number of different multi-user applications, such as chat servers, news and file services, discussion databases, and search engines.

Why Servlets? HTTP is the universal transport of the Internet through restrictive firewalls Browsers, Web Applications, Java technology-based applets and Applications, and other programs can all use HTTP Any kind of data can be transmitted over HTTP - not just HTML

Java Servlets From CGI to Servlet

CGI (Common Gateway Interface) Life Cycle Request for CGI 1 Request for CGI 2 Request for CGI 1 Main Process CGI-based Web Server Child Process for CGI 1 Child Process for CGI 2 Child Process for CGI 1 Example: CGI script written in Perl Each request starts a separate Perl interpreter

FastCGI Life Cycle Request for CGI 1 Request for CGI 2 Main Process Child Process for CGI 1 Child Process for CGI 2 Request for CGI 1 FastCGI-based Web Server FastCGI creates a single persistent process for each FastCGI program.

Server Extension APIs Life Cycle Request for Server Extension 1 Request for Server Extension 2 Main Process Server Extension 1 Server Extension 2 Request for Server Extension 1 Web Server with Server Extension API

Server Extension APIs Examples: Netscape s NSAPI (WAI) Microsoft s ISAPI Apache Modules Server extensions enhance or change the base functionality of the server Proprietary solutions Server-specific APIs use linked C or C++ code Security and reliability hazards

ASP, JavaScript Active Server Pages - ASP (Microsoft): Technique for developing dynamic web content; HTML page contains snippets of embedded code (VBScript, Jscript, etc.); Supported by Microsoft IIS (Internet Information Server) and other web servers. Server-side JavaScript - SSJS (Netscape): Technique for developing dynamic web content; HTML page contains snippets of embedded JavaScript code; For higher performance the web pages are precompiled.

Java Servlet Life Cycle Main Process Request for Servlet 1 Request for Servlet 2 Thread Thread Thread JVM Servlet 1 Servlet 2 Request for Servlet 1 Java Servlet-based Web Server

Servlet Advantages over CGI Efficient Threads instead of OS processes, one servlet copy, persistence Convenient Many high-level utilities Powerful Sharing data, pooling, persistence Portable run on virtually all operating systems and servers Secure No shell escapes, no buffer overflows

Servlet Advantages over CGI Architecturally Faster than CGI Servlets don t fork a new process for each request Servlets are loaded and ready for each request The same servlet can handle many requests Easy to Develop Based on Java programming language No pointer problems like C code No different dialects of development language for different databases Object Oriented Servlets lend themselves to reusable code practices

Servlet Advantages over CGI Extensive Java Libraries Available The functionality of the Java platform libraries make Servlets the most flexible middle tier Servlets can take advantage of JDBC, EJB, JMS, JavaMail, JavaIDL, RMI, and more Any third-party Java technology-based library is easily accessible Write Once, Run Anywhere Servlets can run on any platform that the Java Runtime exists The same servlet can run on any brand of server Develop on any small desktop machine, Deploy on the largest of servers

Free Servlet and JSP engines Apache Tomcat http://jakarta.apache.org/tomcat/ SUN JSWDK http://java.sun.com/products/servlet/download.html/ IBM WebSphere Application Server http://www.software.ibm.com/webservers Allaire JRUN http://www.jrun.com/ Unify ServletExec http://www.servletexec.com Gefion Software LiteWebserver http://www.gefionsoftware.com/litewebserver/ Servlet Engines

Compiling and Invoking Servlets Set CLASSPATH Servlet JAR file (e.g. servlet.jar) JSP JAR file (e.g. jasper.jar, jspengine.jar, jsp.jar) top of your package hierarchy Put servlet class path on proper location (location depends on server) e.g.: TOMCAT: host/webapps/root/web-inf/classes Invoke servlets: http://host/servlet/servletname

Servlet Engines for Existing Servers Standalone Servlet Engines Servers with built-in support for servlets: Sun Microsystem Java Web Server, Netscape Enterprise Server, W3C Jigsaw Server, O'Reilly WebSite Pro Add-on Servlet Engines Plug-in to an existing server: Apache Tomcat, WAICoolRunner for Netscape, Life Software JRun Embeddable Servlet Engines Lightweight servlet platform that can be embedded in another application: Sun Microsystem JavaServer Engine

Three-tier Architecture Presentation Level Clients Content Level Web Server Data and Service Level Relational Database Three-tier architecture for application service providers (ASP): focused on accessing information.

Multitier Architecture Presentation Level Clients Content Level Web Server Application Level Application Server Data and Service Level Relational Databases Multitier (Internet-based) architecture for application service providers (ASP): focused on accessing application services. Other Systems

Three-tier servlet model Java Web Server Servlet Servlet DB Server Custom AS Web Clients Servlet ORB DB: Database Server AS: Application Server ORB: Object Request Broker

Java Servlets Client HTTP-Server Database Browsers Servers Applets Servlets

Java Servlets Operating System Server Service e.g. HTTP Servlet Service e.g. FTP Servlet Servlet Servlet

Servlet Package / Servlet API The javax.servlet package provides interfaces and classes for writing servlets. All servlets implement the Servlet interface. Most common way: extending a class that implements the Servlet interface (e.g. HttpServlet).

The Servlet Interface Servlet GenericServlet HttpServlet MyServlet Servlet Documentation

Client Interaction Client Call Servlet Servlet receives two objects: 1. ServletRequest: encapsulates the communication from the client to the server. 2. ServletResponse: encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package

HTTP Hypertext Transport Protocol HTTP: Stateless protocol (simple) Client specifies HTTP command (method) request also specifies URL and HTTP version Example: GET command GET /example.html HTTP/1.0 URL (address) Protocol version

HTTP Request After the initial request the client can send optional information about the request (software, content type, etc.): Example: Optional header information User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95) Accept: image/gif, image/jpeg, text/*, */* User-Agent header: Information about the client software Accept header: Specification of the media (MIME)

HTTP Request Request Information Example Method: GET Request URI: /dispert/servlet/requestinfoexample Protocol: Path Info: HTTP/1.0 null Remote Address: 149.222.10.2

HTTP Request Request Header Example Host 149.222.51.80:8080 Referer http://149.222.51.80:8080/ dispert/servlets/index.html Accept-Encoding gzip Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* Connection Keep-Alive Accept-Charset iso-8859-1,*,utf-8 User-Agent Mozilla/4.7 [en] (Win98; U) Accept-Language en Ref.: W3C The Referer request-header field allows the client to specify, for the server's benefit, the address (URI) of the resource from which the Request-URI was obtained (the "referrer", although the header field is misspelled.)

HTTP Request After the headers, the client sends a blank line. The client can also send additional data, if this is appropriate for the method being used (e.g. with the POST method). After the client sends the request, the server processes it and sends back a response The first line is a status line that specifies the server's HTTP version, a status code and the code description, e.g.: HTTP/1.0 200 OK

HTTP Response Response Header: Status code (line), status description Examples: HTTP/1.0 200 OK Status code: 200 Request was successful HTTP/1.0 404 Not Found Status code: 404 Requested document was not found

HTTP Response Response Headers: Software running on server Content type of server response Example: Date: Sunday 16-June-2013 04:14:12 GMT Server: JavaWebServer/1.1.1 MIME-Version: 1.0 Content-type: text/html Content-length:1029 Last-modified: Thursday 9-May-2013 12:15:35 GMT

HTTP Methods GET Method for getting information (e.g. document, DB query result) POST Method for posting (sending) information (e.g. credit card information, DB data) HEAD similar to get, used to receive only the response headers PUT DELETE TRACE OPTIONS

GET / POST - Requests GET query string limited to (about) 240 characters should not be used for critical applications (e.g. place orders, update a databases). POST used to send megabytes of information (work around problems with overly-long URLs). URL does not change cannot be bookmarked or emailed (security)

Other HTTP Requests HEAD Client sees only header of response to determine size, etc. PUT used to place documents directly on server DELETE Opposite of PUT TRACE Debugging aid returns to client contents of it's request OPTIONS returns options that are available on server

HEAD Method The HTTP HEAD method is similar to the HTTP GET method, except that the server only returns the header information. HEAD is often used to check: The last-modified date of a document on the server for caching purposes The size of a document before downloading (so the browser can present progress information) The server type, allowing the client to customize requests for that server The type of the requested document, so the client can be sure it supports it

HTTP Response Codes Code Groups: 2xx - Success 3xx - Redirection 4xx - Client error 5xx - Server error

HTTP Response Codes 200-series HTTP response codes indicate that the request was processed without any error conditions. The 200-series responses other than 200 are seldom seen in practice. Code 200 201 202 203 204 Function OK Created Accepted Partial Information No Response Description Following a POST command, this indicates success, but the text of the response line indicates the URL of the new document. Request accepted for asynchronous processing. Returned information may be cached or private. Used for scripts that don't return a visible result.

HTTP Response Codes 300-series response codes indicate that the document requested has moved to some other location, or that the browser is being redirected for some other reason. Code 301 302 303 304 Function Moved Found Method Not modified Description Browsers with link editing capabilities should automatically link to the new reference. The response contains one or more header lines of the form URI: url string CrLf which specify alternative addresses for the object in question. The string is an optional comment field. Same as move, except that linking to the found address doesn't make much sense, since the document URL is expected to change. This is the code that the httpd returns for a cgi script whose output contained a Location: header. Same as found, but a different method may be used to access the document; details about the method are sent in the message body. Use the local copy if you cached it. Often seen when using the HEAD method, rather than the GET method.

HTTP Response Codes 400-series messages indicate that the browser did something wrong. Code 400 401 402 403 404 Function Bad Request Unauthorized Payment Required Forbidden Not found Description Impossible request or syntax error Request should be retried with proper authorization header. This is the response which triggers the browser to pop up the dialog requesting your username and password. Request should be retried with proper charge-to header. Authorization will not help A document with that URL doesn't exist.

HTTP Response Codes 500-series messages indicate that something went wrong on the server. Usually associated with CGI problems. Code 500 501 502 Function Internal Error Not implemented Timed out Description A rather meaningless catch-all message that indicates that the site admin goofed on their CGI program. Another rather ambiguous message, typically meaning that you tried to execute something that was not executable, or POST to someting that was not a CGI program, or something similar. Not in the HTTP spec, but implemented by some HTTP servers. Hypertext Transfer Protocol -- HTTP/1.1 http://www.w3.org/protocols/ http://www.w3.org/protocols/rfc2616/rfc2616.txt

HTTP Response Codes Example:

The Servlet API HTTP Servlets: Servlets use classes and interfaces from the following two packages: javax.servlet supports generic, protocol-independent servlets javax.servlet.http adds HTTP-specific functionality to servlets javax: top-level package name to indicate a standard extension

Generic and HTTP Servlet Servlet construction: Every servlet must implement the javax.servlet.servlet interface. Possibilities: a) Protocol-independent servlet: Extend (subclass) the class javax.servlet.genericservlet b) HTTP-Servlet: Extend (subclass) the class javax.servlet.http.httpservlet

Generic and HTTP Servlet Servlet properties: Similar to an applet a servlet does not have a "main() method" The server invokes certain methods When the server dispatches a request to the servlet the "service() method" is invoked Generic Servlet: overrides the "service() method" to handle requests HTTP Servlet: overrides the "doget() method" to handle GET requests overrides the "dopost() method" to handle POST requests

Servlet Function Read data sent by the user from HTTP form, applet, or custom HTTP client Look up HTTP request information Browser capabilities, cookies, requesting host, etc Generate the results JDBC API, RMI, direct computation Format the results inside a document HTML, excel, etc. Send HTTP response parameters MIME types, cookies, compression, etc. Send the document to the client

Request and Response Request HTTP request header InputStream or Reader Form data, CGI data Response HTTP response header OutputStream or Writer Setting cookies, redirect, or error pages

The Request Object Encapsulates all information from the client Allows access to: request headers InputStream or Reader CGI like information Form data

Frequently Used Request Methods javax.servlet.servletrequest { Enumeration getparameternames(); String getparameter(string paramname); String getremoteaddr(); } javax.servlet.http.httpservletrequest { String getrequesturi(); Enumeration getheadernames(); String getheader(string headername); HttpSession getsession(); Cookie[] getcookies(); } Enumeration

Retrieving Information HttpServletRequest offers several methods to access information about: initialization parameters the server the client request parameters

The Response Object Encapsulates all communication to client Allows access to: response headers an OutputStream or Writer to setting cookies Methods for sending redirects, error pages, etc.

Frequently Used Response Methods javax.servlet.servletresponse { ServletOutputStream getouputstream(); PrintWriter getwriter(); void setcontenttype(string type); void setcontentlength(int length); } javax.servlet.http.httpservletresponse { void addcookie(cookie cookie); void setstatus(int statuscode); void senderror(int statuscode); void sendredirect(string url); }

HttpServletResponse HttpServletResponse Object getwriter() returns a Writer for text getoutputstream() returns ServletOutputStream for binary Set header data before above IO set setcontenttype in header

Reasons for NOT overriding Service() Possible to add support for other services later by adding doput, dotrace, etc. Not possible with service() override Possible to add a getlastmodified method, in order to add support for modification dates Built-in version provides automatic support for HEAD requests OPTION requests TRACE requests

Generic Servlet Server GenericServlet subclass Request Response service() implemented by subclass

Servlet Life-Cycle Three phases of the Servlet Life-Cycle: Initialization: accepts configuration and initializes the state; Service: processes user requests, returns output; Destruction: preparations for shutdown, release of memory resources.

Servlet Life-Cycle Create Initialize Initialization failed Available For Service Unavailable For Service Servicing Requests UnavailableException thrown Destroy Unload

Servlet Life-Cycle Life-Cycle Methods: init (ServletConfig) service (ServletRequest, ServletResponse) destroy () Additional Methods: getservletconfig () getservletinfo ()

Servlet Life-Cycle Comparison Applet Life-Cycle: init () start () stop () destroy () Similarity between servlets and applets is intentional. Servlets are to web servers what applets are to web browsers.

Methods of Servlet init (ServletConfig config) This method is invoked when the servlet is loaded the first time. The ServletConfig object provides initialization arguments for the servlet. servlet (ServletRequest req, ServletResponse res) This method is the main method of the servlet. Each request from a client results in a call to servlet(). The objects ServletRequest and ServletResponse represent the data from the client and to the client. destroy () This method is called before the servlet is unloaded (e.g. for cleanup purposes).

SampleServlet import java.io.*; import javax.servlet.*; public class SampleServlet implements Servlet { private ServletConfig config; public void init (ServletConfig config) throws ServletException { this.config = config; } public void destroy() {} // no action public ServletConfig getservletconfig() { return config; } public String getservletinfo() { return " First simple servlet"; } continued

SampleServlet public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setcontenttype ("text/html"); PrintWriter out = res.getwriter(); } } out.println ("<HTML><HEAD><TITLE> Helmut Dispert - Sample Servlet</TITLE></HEAD>"); out.println ("<BODY><H2> Fachbereich Informatik und Elektrotechnik</H2>"); out.println ("<BODY><H2>First Sample Servlet</H2>"); out.println ("</BODY></HTML>"); out.close();

Initializing Servlets Common in real-life servlets e.g. Initializing database connection pools There are two version of init() Version 1: takes no parameter Version 2: takes a ServletConfig ServletConfig.getInitParameter is used to read initialization parameters init should be used even when no initialization parameters are read

ServletConfig - Initialization Information During servlet start-up initialization information (name/value pairs) is made available and passed to the servlet via the ServletConfig parameter of the init() method String message; public void init(servletconfig config) { message = config.getinitparameter("message"); } ServletConfig http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/servletconfig.html

ServletConfig- Initialization Information Initialization with Jakarta-Tomcat: web.xml <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> (partial listing) <init-param> <param-name>message</param-name> <param-value>fh-kiel</param-value> </init-param> <init-param> <param-name>repeats</param-name> <param-value>5</param-value> </init-param>

Servlet Context Information public abstract interface ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a.war file.) In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. ServletContext http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/servletcontext.html

Servlet Config Information public abstract interface ServletConfig A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. ServletContext http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/servletcontext.html

Server Context Information Server Context information is made available through the ServletContext object. A servlet can obtain this object by calling the getservletcontext() method on the ServletConfig object. This reference should be saved in a private variable within the init() method. private ServletConfig config; public void init (ServletConfig config) { this.config = config; // store config servletcontext sc = config.getservletcontext (); sc.log ("Started OK!"); } ServletContext http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/servletcontext.html

Methods of ServletContext getattribute () Get server information. getmimetype () Return MIME type of a file. getrealpath () Translate relative or virtual path to a path relative to the HTML document root location. getserverinfo () Return name and version of server. getservlet () Return Servlet object of given name. getservletnames () Return an enumeration of servlet names. log () Write information to a servlet log file (server specific).

Servlet Context during Service Request Service requests can contain information in form of name/value parameter pairs as a ServletInputStream or a BufferedReader. This information is available through the ServletRequest object that is passed to the service() method. BufferedReader reader; String param1, param2; public void service {ServletRequest req, ServletResponse res) { reader = req.getreader (); param1 = req.getparameter ("First"); param2 = req.getparameter ("Second"); }

Methods of ServletRequest getattribute () Returns value of a named attribute for this request. getcontentlength() Size of request, if known. getcontenttype() Returns MIME type of the request message body. getinputstream() Returns an InputStream for reading binary data from the body of the request message. getparameter("name") Returns the value of a request parameter as a String, or null if the parameter does not exist. getparameters ("name") Returns an array of URL-decoded values of all occurrences of name in query string or null if the parameter does not exist. continued

Methods of ServletRequest getparameternames() Returns an array of strings with the names of all parameters. getparametervalues() Returns an array of strings for a specific parameter name. getprotocol() Returns the protocol and version for the request as a string of the form <protocol>/<major version>.<minor version>. getreader() Returns a BufferedReader to get the text from the body of the request message. continued ServletRequest http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/servletrequest.html

Methods of ServletRequest getremotehost() Host name of the client machine that sent this request. getscheme() Returns the scheme used in the URL for this request (for example, https, http, ftp, etc.). getservername() Name of the host server that received this request. getserverport() Returns the port number used to receive this request getrealpath() Returns actual path for a specified virtual path. getremoteaddr() IP address of the client machine sending this request.

The javax.servlet package java.io InputStream javax.servlet ServletInputStream Servlet OutputStream Serializable java.lang Object ServletOutputStream GenericServlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel Exception Exception UnavailableException CLASS extends ABSTRACT CLASS implements INTERFACE

HTTP Support Very common: Servlets that use HTTP (Hypertext Transport Protocol). Supporting Package: javax.servlet.http

HTTP Servlet GET Request Response POST Request Response Web Server HttpServlet subclass doget() service() dopost() implemented by subclass

HTTP Servlet (HEAD) HTTP servlet handling a HEAD request: GET Request Response Web Server HttpServlet subclass doget() POST Request Response HEAD Request Response service() dopost() dohead() Body suppressed

Client Interaction Override methods to handle HTTP requests: doget: handling GET, conditional GET and HEAD requests; dopost: handling POST requests; doput: handling PUT requests; dodelete: handling Delete requests.

The javax.http.servlet package java.util javax.http.servlet EventObject HttpSessionBindingEvent EventListener java.io Serializable java.lang Object Cloneable HttpUtils Cookie javax.servlet GenericServlet Servlet ServletRequest ServletResponse HttpSessionBindingListener HttpSession HttpSessionContext HttpServlet HttpServletRequest HttpServletResponse CLASS extends ABSTRACT CLASS implements INTERFACE

A Simple Servlet "Hello World" public class HelloServlet extends HttpServlet { public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/plain"); PrintWriter out = response.getwriter(); out.println("hello World!"); } }

A Simple Servlet "Hello World" Construction of the "HelloWorld" Servlet: The Servlet "HelloServlet" extends the HttpServlet class; HelloServlet overloads the "doget() method", which is invoked every time the web server receives a GET request; The objects "HttpServletRequest" and "HttpServletResponse" are passed to the "doget() method";

A Simple Servlet public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setcontenttype("text/html"); // then write the data of the response out = response.getwriter(); } out.println("<html><head><title>"); out.println(title); out.println("</title></head><body>"); out.println("<h1>" + title + "</H1>"); out.println("<p>this is output from SimpleServlet."); out.println("</body></html>"); out.close(); }

Servlet Request Headers import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowReqHd extends HttpServlet { public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype ("text/html"); PrintWriter out = response.getwriter(); out.println ("<HTML><HEAD><TITLE>Helmut Dispert - Request Headers</TITLE></HEAD>"); out.println ("<BODY><H2>HTTP Request Headers</H2>"); out.println ("<BR><B>Request Method:</B> " + request.getmethod()); out.println ("<BR><B>Request URI:</B> " + request.getrequesturi()); out.println ("<BR><B>Request Protocol:</B> " + request.getprotocol() + "<P>"); out.println ("<TABLE BORDER='1'><TR><TH>Header Name</TH><TH>Header Value</TH></TR>"); } } Enumeration headernames = request.getheadernames(); while (headernames.hasmoreelements()) { String headername = (String) headernames.nextelement(); out.println ("<TR><TD>" + headername + "</TD>"); out.println ("<TD>" + request.getheader(headername) + "</TD></TR>"); } out.println ("</TABLE></BODY></HTML>"); deflate: http://tools.ietf.org/html/rfc1951

Servlet Request Headers accept-encoding SDCH: Shared Dictionary Compression over HTTP (new HTTP 1.1 extension )

Examples: Form Handling with GET/POST Get Request http://149.222.51.81:8180/home-tomcat/servlets/showparametersgetform.html Post Request http://149.222.51.81:8180/home-tomcat/servlets/showparameterspostform.html

URI, URL, URN URI: Uniform Resource Identifier. The generic set of all names/addresses that are short strings that refer to resources. URL: Uniform Resource Locator. An informal term (no longer used in technical specifications) associated with popular URI schemes: http, ftp, mailto, etc. URN: Uniform Resource Name. - An URI that has an institutional commitment to persistence, availability, etc. This sort of URI may also be a URL (example: PURI). - A particular scheme, urn:, specified by RFC2141 and related documents, intended to serve as persistent, locationindependent, resource identifiers. RFC 2396 - Uniform Resource Identifiers (URI): Generic Syntax

URI, URL, URN UR* Terms URLs http: ftp:... urn: URIs URNs

URI, URL, URN Both URLs and URNs are URIs Expansions: PURL - Persistent Uniform Resource Locator http://purl.oclc.org/ URC: Uniform Resource Characteristics URA: Uniform Resource Agent PURL PURLs are Persistent Uniform Resource Locators (URLs). A URL is simply an address on the World Wide Web. A Persistent URL is an address on the World Wide Web that points to other Web resources. If a Web resource changes location (and hence URL), a PURL pointing to it can be updated. A user of a PURL always uses the same Web address, even though the resource in question may have moved. http://purl.oclc.org/

Unicode, UCS, and UTF-8 http://www.unicode.org/

Unicode, UCS, and UTF-8 http://www.unicode.org/ UCS and ISO 10646 (ISO/IEC 10646-1) The international standard ISO 10646 defines the Universal Character Set (UCS). UCS is a superset of all other character set standards. UCS and Unicode are code tables that assign integer numbers to characters. UCS-2 and UCS-4: store Unicode text as sequences of either 2 or 4 bytes.

The Unicode Standard The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages of the modern world. In addition, it supports classical and historical texts of many written languages. The Unicode Standard, Version 3.1 The primary feature of Unicode 3.1 is the addition of 44,946 new encoded characters. Together with the 49,194 already existing characters in Unicode 3.0, that comes to a grand total of 94,140 encoded characters in Unicode 3.1. The new characters cover several historic scripts, several sets of symbols, and a very large collection of additional CJK ideographs. Unicode 3.1 also features new Unicode character properties, and assignments of property values for the much expanded repertoire of characters. http://www.unicode.org/unicode/reports/tr27/

Unicode, UCS, and UTF-8 ASCII or Latin-1 can be transformed into UCS-2 by inserting a 0x00 byte in front of every ASCII byte. In case of UCS-4 three 0x00 bytes have to be inserted before every ASCII byte. UCS-4 UCS-2 ASCII 0 0 0 0 0 0 0 0 0 x x x x x 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 x x x x x x x x x 8 8 8 8 ISO 10646 is designed as a 31-bit character set (with possible code positions ranging from \u00000000 to \u7fffffff),. Basic Multilingual Plane (BMP): First 2 16 (64k) character positions (ISO 10646-2, Unicode 3.1). UCS-4 can represent all UCS and Unicode characters, UCS-2 can represent only those from the BMP (\u0000 to \uffff).

ISO-8859-1 (Latin-1) \uffff Unicode \u00ff ISO-8859-1 #255 \u0000 \u0000 #0 (diagrams are not to scale)

ISO-8859-15 (Latin-9) The ISO Latin 9 (ISO 8859-15) character set differs from ISO Latin 1 (ISO 8859-1) character set in a few positions only. The Euro sign and some national letters used e.g. in French and Finnish have been introduced and some rarely used special characters omitted. Differences between Latin-1 and Latin-9 Position 0xA4 0xA6 0xA8 0xB4 0xB8 0xBC 0xBD 0xBE 8859-1 ¼ ½ ¾ 8859-15 Š š Ž ž Œ œ Ÿ

UTF-8 Properties of UTF-8 (UCS Transformation Format): UCS characters \u0000 to \u007f (ASCII) are encoded as bytes 0x00 to 0x7F (ASCII compatibility). Therefore files and strings which contain only 7-bit ASCII characters have the same encoding under both ASCII and UTF-8. All UCS characters > \u007f are encoded as a sequence of several bytes, each of which has the most significant bit set. Therefore, no ASCII byte (0x00-0x7F) can appear as part of any other character. The first byte of a multibyte sequence that represents a non-ascii character is always in the range 0xC0 to 0xFD and it indicates how many bytes follow for this character. All further bytes in a multibyte sequence are in the range 0x80 to 0xBF. This allows easy resynchronization and makes the encoding stateless and robust against missing bytes. UTF-8 encoded characters may theoretically be up to six bytes long, however 16-bit BMP characters are only up to three bytes long. The bytes 0xFE and 0xFF are never used in the UTF-8 encoding. RFC 2279: UTF-8, a transformation format of ISO 10646

UTF-8 UTF-8 definition (from RFC 2279): In UTF-8, characters are encoded using sequences of 1 to 6 octets. The only octet of a "sequence" of one has the higher-order bit set to 0, the remaining 7 bits being used to encode the character value. In a sequence of n octets, n>1, the initial octet has the n higher-order bits set to 1, followed by a bit set to 0. The remaining bit(s) of that octet contain bits from the value of the character to be encoded. The following octet(s) all have the higher-order bit set to 1 and the following bit set to 0, leaving 6 bits in each to contain bits from the character to be encoded.

UTF-8 Encoding from UCS-4 to UTF-8: UCS-4 range (hex.) UTF-8 octet sequence (binary) 0000 0000-0000 007F 0xxxxxxx 0000 0080-0000 07FF 110xxxxx 10xxxxxx 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 0400 0000-7FFF FFFF 1111110x 10xxxxxx... 10xxxxxx RFC 2279: UTF-8, a transformation format of ISO 10646

HTML Character Entities import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain extends HttpServlet { public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype ("text/html"); PrintWriter out = res.getwriter(); res.setheader ("Content-Language", "es"); } out.println("<html><head><title>en Español</TITLE></HEAD>"); out.println("<body>"); out.println("<h2> En Español:</H2>"); out.println("<h2> Hola Mundo!"); out.println("</body></html>"); } named character entity ñ

HTML Character Entities import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain2 extends HttpServlet { public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype ("text/html"); PrintWriter out = res.getwriter(); res.setheader ("Content-Language", "es"); } out.println("<html><head><title>en Español</TITLE></HEAD>"); out.println("<body>"); out.println("<h2> En Español:</H2>"); out.println("<h2> Hola Mundo!"); out.println("</body></html>"); } numbered character entity ñ

Unicode Escapes import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain3 extends HttpServlet { public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype ("text/html"); PrintWriter out = res.getwriter(); res.setheader ("Content-Language", "es"); } out.println("<html><head><title>en Espa\u00f1ol</TITLE></HEAD>"); out.println("<body>"); out.println("<h2> En Español:</H2>"); out.println("<h2> Hola Mundo!"); out.println("</body></html>"); } Unicode escape sequence \u00f1

Internationalization - Charsets PrintWriter uses as the default charset ISO-8859-1 (Latin-1) Specify alternate charset: Example: Chinese charset: res.setcontenttype ("text/html; charset=gb2312"); PrintWriter out = res.getwriter (); // Chinese

Internationalization - Charsets Language Chinese (Traditional/Taiwan) English German Greek Japanese Korean Polish Russian Turkish Code zh-cn zh (TW) en de el ja ko pl ru tr Charset Big5, gb2312 ISO-8859-1 ISO-8859-1 ISO-8859-7 Shift_JIS, ISO-2022-JP, EUC-JP EUC-KR ISO-8859-2 ISO-8859-5, KOI8-R ISO-8859-9

Internationalization - Charsets import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloChinaReader extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/plain; charset=gb2312"); PrintWriter out = res.getwriter(); res.setheader("content-language", "zh-cn"); Locale locale = new Locale("zh-CN", ""); DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

Internationalization - Charsets out.println("in Chinese:"); try { FileInputStream fis = new FileInputStream( req.getrealpath("helloworld.gb2312")); InputStreamReader isr = new InputStreamReader(fis, "gb2312"); BufferedReader reader = new BufferedReader(isr); String line = null; while ((line = reader.readline())!= null) { out.println(line); } } catch (FileNotFoundException e) { // No Hello for you } out.println(full.format(new Date())); } }

HTTP - continued HTTP Support Classes Package javax.servlet.http to write HTTP servlets. The abstract class javax.servlet.http.httpservlet provides an implementation of the javax.servlet.servlet interface and includes default functionality. Easiest way to write an HTTP servlet: Extend HttpServlet and add custom processing. The class HttpServlet provides an implementation of the service() method that dispatches the HTTP messages to one of the special methods (i.e. HTTP protocol methods): doget() dohead() dodelete() dooptions() dopost() dotrace()

HTTP - continued The service() method interprets each HTTP method and determines if it is an HTTP GET, HTTP POST, HTTP HEAD, or other protocol method: HTTP Client Hosting Server service () HttpServlet Dispatching HTTP requests: doget () dohead () dodelete () dooptions () dopost () dotrace ()

Server-Side Include (SSI) with Servlets Request Response Web Server.shtml file <HTML> <HEAD>... </HEAD> <BODY> <SERVLET CODE=Servlet1> </SERVLET> Servlet1... </BODY> </HTML>

Server-Side Include (SSI) with Servlets <HTML> <HEAD><TITLE>Time Program</TITLE></HEAD> <BODY> Current local time: <SERVLET CODE = "CurrentTime"> </SERVLET> Current time in New York: <SERVLET CODE = "CurrentTime"> <PARAM NAME = "zone" VALUE = "EST"> </SERVLET> </BODY> </HTML>

Server-Side Include (SSI) with Servlets import java.io.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class CurrentTime extends HttpServlet { public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getwriter(); Date date = new Date (); DateFormat df = DateFormat.getInstance (); String zone = req.getparameter("zone"); if (zone!= null) { TimeZone tz = TimeZone.getTimeZone (zone); df.settimezone(tz); } out.println (df.format (date)); } }

Servlet Chaining Request Web Server Servlet1 Servlet2 Response Servlet3 Servlet Chaining: The output from each servlet is passed (piped) as input to the next servlet.

Servlet Filters Filter Component: A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters provide the ability to encapsulate recurring tasks in reusable units (modular code). can be used to transform the response from a servlet. A common task for the web application is to format data sent back to the client, e.g. when formats other than just HTML are required (for example, WML). http://java.sun.com

Servlet Filters Filter Applications: Authentication: blocking requests based on user identity. Logging and auditing: tracking users. Image conversion: scaling, etc. Data compression: to reduce download time. Localization (i.e. targeting particular locales). Transformation of XML content (XSL/T ) Encryption. Tokenizing. Triggering resource access events. Mime-type chaining Caching. http://java.sun.com

Session Session Session Tracking Cookies

Session Tracking Background: HTTP is a stateless protocol: HTTP does not provide any way for a server to recognize that a sequence of requests comes from the same client. Example (E-Commerce - Shopping cart): Client at an on-line store adds items. How can the server know what is already in the cart? Client proceeds to checkout. How can the server include a previously created shopping cart? Session Tracking: Maintain state about series of requests from same client over time

Session Tracking Possible ways for session tracking: Cookies URL-rewriting Hidden form fields

Session Tracking Traditional Approaches: User Authorization user has to register for an account and then login getusername() Hidden form fields fields are added to an HTML form URL rewriting http://server:port/servlet/rewritten http://server:port/servlet/rewritten/123 http://server:port/servlet/rewritten?sessionid=123

Cookies Cookie: Small piece of textual information that is sent from a server to a browser. The server can read the information back, in order to get information about the client's previous visit. Characteristics of Cookies: Key-value pairs Way for server to store information on client Server appends to HTTP response headers Client appends to HTTP request headers Cookies are single-valued

Cookies Benefits of Cookies: User Identification Storing User ID (Username) and Password Customize a Web-Site Allow client specific (focused) advertising

Cookies Using Cookies: Idea Servlet sends a cookie name and value to client Client returns same name and value when it connects to same site (or same domain, depending on cookie setting) Typical applications of Cookies Identifying a user during an e-commerce session (Servlets provide API) Avoiding username and password Focusing advertising

Using Cookies To send Cookie instantiate Cookie Object set attributes send the cookie Get information from Cookie retrieve all cookies from the user s request find cookie with specified name get values from cookies

Creating a Cookie Constructor for javax.servlet.http.cookie creates a cookie with an initial name and value cookie value can later be changed with the setvalue method. the value of the cookie can be any String (null value is not guaranteed to work on all browsers). If the servlet returns a response to the user with a Writer, Cookie has to be created before accessing the Writer.

Cookie Constructor public Cookie(java.lang.String name, java.lang.string value) Constructs a cookie with a specified name and value. The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation. The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be changed after creation with the setvalue method. By default, cookies are created according to the Netscape cookie specification. The version can be changed with the setversion method. Parameters: name - a String specifying the name of the cookie value - a String specifying the value of the cookie Throws: java.lang.illegalargumentexception - if the cookie name contains illegal characters (for example, a comma, space, or semicolon) or it is one of the tokens reserved for use by the cookie protocol See Also: setvalue(java.lang.string), setversion(int)

Cookie Constructor RFC2109 Status of this Memo HTTP State Management Mechanism This document specifies an Internet standards track protocol for the Internet community, and requests discussion and suggestions for improvements. Please refer to the current edition of the "Internet Official Protocol Standards" (STD 1) for the standardization state and status of this protocol. Distribution of this memo is unlimited. 1. ABSTRACT This document specifies a way to create a stateful session with HTTP requests and responses. It describes two new headers, Cookie and Set-Cookie, which carry state information between participating origin servers and user agents. The method described here differs from Netscape's Cookie proposal, but it can interoperate with HTTP/1.0 user agents that use Netscape's method. ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt

Creating a cookie : Example (Shopping Cart) public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { //Check for pending adds to the shopping cart String bookid = req.getparameter("buy"); // customer wants to add a book to cart: // add a cookie if (bookid!= null) { Cookie getbook = new Cookie("Buy", bookid); }...

Sending a cookie public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException {... if (bookid!= null) { Cookie getbook = new Cookie("Buy", bookid); getbook.setcomment("customer - Books"); res.addcookie(getbook); }... Cookie http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/cookie.html

Reading/Deleting a cookie: Example String bookid - req.getparameter("remove");... if (bookid!= null) { // Find correct cookie (book) Cookie[] cookies = req.getcookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getname().equals("buy") && c.getvalue().equals(bookid)) { // Delete cookie setting maximum age to zero c.setmaxage(0); } getcookies() http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/httpservletrequest.html#getcookies()

Cookie Methods getdomain () / setdomain () Specifies domain to which cookie applies. Current host must be part of domain specified. getmaxage () / setmaxage () Gets/sets the cookie expiration time (in seconds). If not set, cookie applies to current browsing session only. getname () / setname () Gets/sets the cookie name. For new cookies, name is supplied to constructor.

Cookie Methods getpath () / setpath () Gets/sets the path to which cookie applies. If unspecified, cookie applies to URLs that are within or below directory containing current page. getsecure () / setsecure () Gets/sets flag indicating whether cookie should apply only to SSL connections. getvalue () / setvalue () Gets/ sets value associated with cookie.

Problems with Cookies Problem: privacy - not security Servers can remember previous action Server can link personal information to previous action Servers can share cookie information through use of a cooperating third party like "doubleclick.net" Badly designed site can store sensitive information (e.g. credit card numbers) directly in cookie Some browsers allow hostile sites steal cookies (JavaScript language bugs) Moral for servlet authors Don t depend on cookie being enabled Don t put sensitive information in cookies

Cookie Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieExample extends HttpServlet { } public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); } // print out cookies Cookie[] cookies = request.getcookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getname(); String value = c.getvalue(); out.println(name + " = " + value); } // set a cookie String name = request.getparameter("cookiename"); if (name!= null && name.length() > 0) { String value = request.getparameter("cookievalue"); Cookie c = new Cookie(name, value); response.addcookie(c); }

Cookie Example - Set Cookies import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SetCook extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addcookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); } } cookie.setmaxage(3600); response.addcookie(cookie); } response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); String title = "Setting Cookies"; out.println ("<BODY>\n" + additional sample text + "</BODY></HTML>");

Cookie Example - Show Cookies import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowCook extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); } } out.println("<body>\n" + "<H1>" + "Show Cookies" + "</H1>\n" + "<TABLE BORDER=1>\n" + "<TR>\n" + " <TH>Cookie Name\n" + " <TH>Cookie Value"); Cookie[] cookies = request.getcookies(); if (cookies!= null) { Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println("<tr>\n" + " <TD>" + cookie.getname() + "\n" + " <TD>" + cookie.getvalue()); } } out.println("</table></body></html>");

Cookie Example - Netscape persistent cookies # Netscape HTTP Cookie File all cookies # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. 149.222.51.80:8080 FALSE /dispert/servlet FALSE 1008271810 Persistent-Cookie-0 Cookie-Value-P0 149.222.51.80:8080 FALSE /dispert/servlet FALSE 1008271810 Persistent-Cookie-1 Cookie-Value-P1 149.222.51.80:8080 FALSE /dispert/servlet FALSE 1008271810 Persistent-Cookie-2 Cookie-Value-P2.amazon.com TRUE / FALSE 1008489380 session-id-time 1008489600.sun.com TRUE / FALSE 1767225385 SUN_ID 149.222.10.12:113901007762577

Cookie Example - Internet Explorer Persistent-Cookie-0 Cookie-Value-P0 149.222.51.80/dispert/servlet/ 0 632833920 29459480 3190006880 29459470 * Persistent-Cookie-1 Cookie-Value-P1 149.222.51.80/dispert/servlet/ 0 632833920 29459480 3190006880 29459470 * Persistent-Cookie-2 Cookie-Value-P2 149.222.51.80/dispert/servlet/ 0 632833920 29459480 3190006880 29459470 * filename: helmut dispert@servlet[2].txt

Session Tracking API The Servlet API provides several methods and classes specifically designed to handle session tracking. Class calls HttpSession Steps Obtain Session for a user Store or get data from session object Invalidate the session (manual or automatic) Shared by all servlets in application

Session Tracking: Obtainig a session Example of a Servlet getting a user session : public class CatalogServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { //Get the user s session HttpSession session = req.getsession(true);... out = res.getwriter(); }... getsession() http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/httpservletrequest.html#getsession()

Storing and Getting data from a session The HttpSession interface provides methods that store and return: standard session properties, such as a session identifier application data, which is stored as a name/value pair, where the name is a String and the value is an Object Important: Because multiple servlets have access to a user s session, a naming convention should be adopted for organizing the names associated with application data. This way it can be avoided that servlets accidentally overwrite each other s value in the session.

Storing and Getting data from a session public class CatalogServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { }... //Get the user s session and shopping cart HttpSession session = req.getsession(true); ShoppingCart cart = (ShoppingCart) session.getvalue(session.getid()); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putvalue(session.getid(), cart);

HttpSession A session can be designated as new A new session causes the isnew method of the HttpSession class to return true, indicating that, for example, the client does not yet know about the session. A new session has no associated data.

HttpSession - Life Cycle Session do not last for ever. A session either expires automatically or manually (e.g. invalidation of a session when there has been no page request in some period of time). To invalidate a session means to remove the HttpSession object and its value from the system. To manually invalidate a session the session s invalidate method is used: session.invalidate()

HttpSession Methods getvalue (), getattribute () Extracts a previously stored value from a session object. Returns null if no value is associated with the given name putvalue (), setattribute () Associate a value with a name removevalue (), removeattribute () Removes values associate with name getvaluenames (), getattributenames () Returns names of all attributes in the session getid () Returns the unique identifier continued Obs.: getvalue() and putvalue() are deprecated

HttpSession Methods isnew () Determines if session is new to client (not page) getcreationtime () Returns time at which session was first created getlastaccessedtime () Returns time at which the session was last sent fom the client invalidate () Invalidate the session and unbind all objects associated with it

HttpSession Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; // Session Tracking Example public class ShowSession extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { continued

HttpSession Example continued response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); HttpSession session = request.getsession(true); String heading; Integer accesscount = (Integer)session.getAttribute("accessCount"); if (accesscount == null) { accesscount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accesscount = new Integer(accessCount.intValue() + 1); } session.setattribute("accesscount", accesscount);

HttpSession Example out.println( "<BODY>\n" + "<H1>" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1>\n" + "<TR>\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getid() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accesscount + "\n" + "</TABLE>\n" + "</BODY></HTML>"); continued

HttpSession Example } /** Handle GET and POST requests identically. */ } public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { doget(request, response); } http://149.222.51.81:8180/home-tomcat/servlet/showsession

HttpSession Example http://149.222.51.81:8180/home-tomcat/servlet/showsession

HttpSession Example http://149.222.51.81:8180/home-tomcat/servlet/showsession