163
Fachbereich Informatik und Elektrotechnik Programming in Java, Helmut Dispert Java Servlets Java Servlet Programming

Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

  • Upload
    vominh

  • View
    219

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java Servlets

Java Servlet Programming

Page 2: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Workgroup

Server

Java Technology

Enabled Desktop

Micro

Edition

Standard

Edition

Enterprise

Edition

High-End

Server

Java Technology

Enabled Devices

JavaCard

Java 2 Platform Editions

Page 3: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java 2 Platform

Java 2

Enterprise

Edition

(J2EE)

Core APIs

Java 2

Enterprise

Edition

(J2EE)

Core APIs

Java 2

Standard

Edition

(J2SE)

Core APIs

Java 2

Standard

Edition

(J2SE)

Core APIs

Java Programming LanguageJava Programming Language

Java HotSpotJava HotSpot Java Virtual Maschine (JVM)Java Virtual Maschine (JVM) KVMKVM Card VMCard VM

Java 2 Micro Edition Core APIsJava 2 Micro Edition Core APIs

TVProfile

TVProfile

ScreenPhoneProfile

ScreenPhoneProfile

CarProfile

CarProfile

PersonalProfile

PersonalProfile

Mobile InformationDevice Profile

Mobile InformationDevice Profile

SmartCard

Profile

SmartCard

Profile

ProfileProfileProfileProfile

ProfileProfileProfileProfile 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.

Page 4: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java Technology / Range of Devices

Page 5: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

J2EE Platform

ToolsTools Application Programming ModelApplication Programming Model

TransactionsTransactions

MessagingMessaging MailMail

Co

nn

ecto

rsC

on

necto

rs

ContainerContainer

EJBsEJBs JSPsJSPs ServletsServlets

Java 2 SDK, Standard EditionJava 2 SDK, Standard Edition

CORBACORBA RMIRMI DatabaseDatabase Naming / DirectoryNaming / Directory

Ap

ple

tsA

pp

lets

Ja

vaB

ean

sJa

vaB

ean

s

Page 6: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 7: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Jakarta - Tomcat

Jakarta Project

The goal of the Jakarta Project is to provide commercial-

quality 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.

Page 8: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Jakarta - Tomcat

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.

Page 9: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Standard Services and APIs

Servlet

Java Server PagesEJB JDBC

Business

LogicPresentationData

Access

DataClient

JTS/JTA JNDI JavaMail RMI-IIOP JMS

Java 2 Enterprise Edition APIs

Page 10: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 11: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

What Are Servlets?

Web Server

Servlet Engine Container

BrowserURL2

URL1

Servlet

2

Servlet

1

Multiple requests

In a single session

Request

Response

Request

Response

Page 12: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 13: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 14: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java Servlets

From CGI to Servlet

Page 15: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

CGI (Common Gateway Interface) – Life Cycle

Main

Process

Request for CGI 1Child Process

for CGI 1

Request for CGI 2Child Process

for CGI 2

Request for CGI 1Child Process

for CGI 1

CGI-based

Web Server

Example: CGI script written in Perl

���� Each request starts a separate Perl interpreter

Page 16: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Main

Process

Request for CGI 1Child Process

for CGI 1

Request for CGI 2Child Process

for CGI 2

Request for CGI 1

FastCGI-based

Web Server

���� FastCGI creates a single persistent process

for each FastCGI program.

FastCGI – Life Cycle

Page 17: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Main Process

Request for

Server Extension 1Server Extension 1

Server Extension 2

Web Server with Server Extension API

Request for

Server Extension 2

Request for

Server Extension 1

Server Extension APIs – Life Cycle

Page 18: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 19: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 20: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Main Process

JVM

Java Servlet – Life Cycle

Request for

Servlet 1Servlet 1

Java Servlet-based Web Server

Servlet 2Request for

Servlet 2

Request for

Servlet 1

Thread

Thread

Thread

Page 21: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 22: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 23: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 24: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 25: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 26: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 27: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Three-tier Architecture

Web ServerContent Level

Relational

DatabaseData and Service Level

Presentation

Level

Clients

Three-tier architecture for application service providers (ASP):

focused on accessing information.

Page 28: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Multitier Architecture

Multitier (Internet-based) architecture for application service providers (ASP):

focused on accessing application services.

Web ServerContent Level

Clients

Presentation

Level

Relational Databases

Data and

Service Level

Other Systems

Application LevelApplication

Server

Page 29: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Three-tier servlet model

DB

Server

Custom

AS

ORB

Java Web

Server

Servlet

Servlet

ServletWeb Clients

DB: Database Server

AS: Application Server

ORB: Object Request Broker

Page 30: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java Servlets

DatabaseHTTP-ServerClient

AppletsBrowsers

ServletsServers

Page 31: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Java Servlets

Operating System

Server

Service

e.g. HTTP

Service

e.g. FTP

Servlet

Servlet

Servlet

Servlet

Page 32: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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).

Page 33: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

The Servlet Interface

ServletServlet

GenericServletGenericServlet

HttpServletHttpServlet

MyServletMyServlet Servlet Documentation

Page 34: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Client Interaction

ServletClient

� 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.

Call

ServletRequest and ServletResponse are

interfaces defined by the javax.servlet package

Page 35: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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)

Protocolversion

Page 36: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Request

After the initial request the client can send optional

information about the request (software, content type,

etc.):

� Optional header information

Example:

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)

Page 37: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Request

Request Information Example

Method: GET

Request URI:/dispert/servlet/RequestInfoExample

Protocol: HTTP/1.0

Path Info: null

Remote Address: 149.222.10.2

Page 38: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Request

Request Header ExampleHost 149.222.51.80:8080Referer http://149.222.51.80:8080/

dispert/servlets/index.htmlAccept-Encoding gzipAccept image/gif, image/x-xbitmap,

image/jpeg, image/pjpeg,image/png, */*

Connection Keep-AliveAccept-Charset iso-8859-1,*,utf-8User-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.)

Page 39: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 40: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Response

Response Header:

� Status code (line), status description

Examples:

HTTP/1.0 200 OKStatus code: 200

�Request was successful

HTTP/1.0 404 Not FoundStatus code: 404

�Requested document was not found

Page 41: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Response

Response Headers:

� Software running on server

� Content type of server response

Date: Sunday 11-June-2000 04:14:12 GMT

Server: JavaWebServer/1.1.1

MIME-Version: 1.0

Content-type: text/html

Content-length:1029

Last-modified: Thursday 7-May-2000 12:15:35 GMT

Example:

Page 42: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP – Methods

� GETMethod for getting information (e.g. document, DB query

result)

� POSTMethod for posting (sending) information (e.g. credit card

information, DB data)

� HEADsimilar to get, used to receive only the response headers

� PUT

� DELETE

� TRACE

� OPTIONS

Page 43: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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)

Page 44: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 45: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 46: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Response Codes

Code Groups:

� 2xx - Success

� 3xx - Redirection

� 4xx - Client error

� 5xx - Server error

Page 47: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Response Codes

No Response

Partial Information

Accepted

Created

OK

Function

Used for scripts that don't return a visible

result.204

Returned information may be cached or

private.203

Request accepted for asynchronous

processing.202

Following a POST command, this indicates

success, but the text of the response line

indicates the URL of the new document.

201

200

DescriptionCode

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.

Page 48: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Response Codes

Not modified

Method

Found

Moved

Function

Use the local copy if you cached it. Often seen when using

the HEAD method, rather than the GET method. 304

Same as found, but a different method may be used to access

the document; details about the method are sent in the

message body.

303

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.

302

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.

301

DescriptionCode

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.

Page 49: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Response Codes

Authorization will not helpForbidden403

Request should be retried with proper charge-to

header. Payment Required402

Not found

Unauthorized

Bad Request

Function

A document with that URL doesn't exist. 404

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.

401

Impossible request or syntax error 400

DescriptionCode

400-series messages indicate that the browser did something wrong.

Page 50: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Response Codes

Not in the HTTP spec, but implemented by some

HTTP servers. Timed out502

Not implemented

Internal Error

Function

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.

501

A rather meaningless catch-all message that

indicates that the site admin goofed on their CGI

program.

500

DescriptionCode

500-series messages indicate that something went wrong on the server.

Usually associated with CGI problems.

Hypertext Transfer Protocol -- HTTP/1.1http://www.w3.org/Protocols/

http://www.w3.org/Protocols/rfc2616/rfc2616.txt

Page 51: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

The Servlet API

HTTP Servlets:

Servlets use classes and interfaces from the

following two packages:

� javax.servletsupports generic, protocol-independent servlets

� javax.servlet.httpadds HTTP-specific functionality to servlets

javax:

top-level package name to indicate a standard extension

Page 52: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Generic and HTTP Servlet

Servlet construction:Every servlet must implement the

javax.servlet.Servletinterface.

Possibilities:

a) Protocol-independent servlet:Extend (subclass) the class

javax.servlet.GenericServletb) HTTP-Servlet:

Extend (subclass) the class

javax.servlet.http.HttpServlet

Page 53: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 54: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Function

� Read data send 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

Page 55: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 56: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

The Request Object

� Encapsulates all information from the client

� Allows access to:

� request headers

� InputStream or Reader

� CGI like information

� Form data

Page 57: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 58: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Retrieving Information

� HttpServletRequest offers several methods

to access information about:

� initialization parameters

� the server

� the client

� request parameters

Page 59: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 60: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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);

}

Page 61: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HttpServletResponse

� HttpServletResponse Object

� getWriter() returns a Writer for text

� getOutputStream() returns

ServletOutputStream for binary

� Set header data before above IO set

� setContentType in header

Page 62: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 63: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

GenericServlet subclassServer

service()

Generic Servlet

Request

Response

implemented by subclass

Page 64: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 65: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Life-Cycle

Create

Initialize

Available

For

Service

Unavailable

For

Service

Servicing

Requests

Destroy

Unload

Initialization failed

UnavailableException

thrown

Page 66: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Life-Cycle

Life-Cycle Methods:

� init (ServletConfig)

� service (ServletRequest, ServletResponse)

� destroy ()

Additional Methods:

� getServletConfig ()

� getServletInfo ()

Page 67: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 68: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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).

Page 69: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 70: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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();

}

}

Page 71: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.getInitParameteris used to read initialization parameters

� init should be used even when no initialization parameters are read

Page 72: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 73: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

ServletConfig- Initialization Information

<?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>

<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>

Initialization with Jakarta-Tomcat: web.xml

(partial listing)

Page 74: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 75: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 76: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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 ServletConfigobject .

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 configservletContext 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

Page 77: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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).

Page 78: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Context during Service Request

Service requests can contain information in form of name/value parameter pairs as a ServletInputStreamor 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");}

Page 79: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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 ifthe 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

Page 80: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 81: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 82: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

javax.servlet

java.lang

java.io

The javax.servlet package

ServletServlet

GenericServletGenericServletObjectObject

ExceptionException

InputStreamInputStream

OutputStreamOutputStream

ServletInputStreamServletInputStream

ServletOutputStreamServletOutputStreamServletConfigServletConfig

SingleThreadModelSingleThreadModel

ServletContextServletContext

ServletRequestServletRequest

ServletResponseServletResponse

ExceptionException UnavailableExceptionUnavailableException

CLASSCLASS ABSTRACT CLASSABSTRACT CLASS INTERFACEINTERFACE

extends implements

SerializableSerializable

Page 83: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HTTP Support

Very common:

Servlets that use HTTP

(Hypertext Transport Protocol).

Supporting Package: javax.servlet.http

Page 84: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Web

Server

HttpServlet subclass

service()

doGet()

doPost()

HTTP Servlet

implemented by subclass

Request

Response

GET

Request

Response

POST

Page 85: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Web

Server

HttpServlet subclass

service()

doGet()

doPost()

doHead()

HTTP Servlet (HEAD)

GETRequestResponse

POSTRequestResponse

HEADRequestResponse

Body suppressed

HTTP servlet handling a HEAD request:

Page 86: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 87: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

javax.http.servlet

javax.servletjava.lang

The javax.http.servlet package

ObjectObject

HttpSessionHttpSession

CLASSCLASS ABSTRACT CLASSABSTRACT CLASS INTERFACEINTERFACE

extends implements

CloneableCloneable

java.io

java.util

HttpSessionContextHttpSessionContext

HttpSessionBindingListenerHttpSessionBindingListener

SerializableSerializable

EventListenerEventListener

CookieCookie

HttpUtilsHttpUtils

ServletServlet

ServletRequestServletRequest

ServletResponseServletResponse HttpServletResponseHttpServletResponse

HttpServletRequestHttpServletRequest

GenericServletGenericServlet HttpServletHttpServlet

HttpSessionBindingEventHttpSessionBindingEventEventObjectEventObject

Page 88: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

A Simple Servlet – "Hello World"

public class HelloServletextends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException{response.setContentType("text/plain");PrintWriter out = response.getWriter();out.println("Hello World!");}}

Page 89: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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";

Page 90: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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 firstresponse.setContentType("text/html");

// then write the data of the responseout = 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();}

}

Page 91: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 92: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet – Request Headers

accept-encoding SDCH: Shared Dictionary Compression over HTTP

(new HTTP 1.1 extension )

Page 93: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Examples: Form Handling with GET/POST

http://149.222.51.81:8180/home-tomcat/servlets/ShowParametersPostForm.html

http://149.222.51.81:8180/home-tomcat/servlets/ShowParametersGetForm.html

Get Request

Post Request

Page 94: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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, location-

independent, resource identifiers.

RFC 2396 - Uniform Resource Identifiers (URI): Generic Syntax

Page 95: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

URI, URL, URN

UR* Terms

URIs

URLs

URNs

http:ftp:...

urn:

Page 96: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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/

Page 97: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Unicode, UCS, and UTF-8

http://www.unicode.org/

Page 98: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 99: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

The Unicode Standard

http://www.unicode.org/unicode/reports/tr27/

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.

Page 100: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

8 8

0 0 0 0 00 00 0 0 0 0 00 00 0 0 0 0 00 00 0 x x x xx xx

8 8

UCS-4

ASCII

0 0 0 0 00 00 0 x x x xx xx

UCS-2

ISO 10646 is designed as a 31-bit character set (with possible code positions

ranging from \u00000000 to \u7FFFFFFF),.

Basic Multilingual Plane (BMP):

First 216 (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).

Page 101: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

ISO-8859-1 (Latin-1)

Unicode

\uFFFF

\u0000

ISO-8859-1

#0

#255

(diagrams are not to scale)

\u0000

\u00FF

Page 102: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

ŸœŒžŽšŠ€8859-15

¾½¼¸´¨¦¤8859-1

0xBE0xBD0xBC0xB80xB40xA80xA60xA4Position

Differences between Latin-1 and Latin-9

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.

Page 103: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 104: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 105: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 106: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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&ntilde;ol</TITLE></HEAD>");out.println("<BODY>");out.println("<H2> En Espa&ntilde;ol:</H2>");out.println("<H2> &iexcl;Hola Mundo!");out.println("</BODY></HTML>");}

}

HTML Character Entities

named character entity

&ntilde;

Page 107: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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&#241;ol</TITLE></HEAD>");out.println("<BODY>");out.println("<H2> En Espa&ntilde;ol:</H2>");out.println("<H2> &iexcl;Hola Mundo!");out.println("</BODY></HTML>");}

}

HTML Character Entities

numbered character entity

&#241;

Page 108: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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&ntilde;ol:</H2>");out.println("<H2> &iexcl;Hola Mundo!");out.println("</BODY></HTML>");}

}

Unicode Escapes

Unicode escape sequence

\u00f1

Page 109: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Internationalization - Charsets

PrintWriter uses as the default charset

ISO-8859-1 (Latin-1)

Specify alternate charset:

Example: Japanese charset:

res.setContentType ("text/html; charset=Shift_JIS");PrintWriter out = res.getWriter (); // Japanese

Page 110: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Internationalization - Charsets

ISO-8859-9trTurkish

ISO-8859-5, KOI8-RruRussian

ISO-8859-2plPolish

EUC-KRkoKorean

Shift_JIS, ISO-2022-JP,

EUC-JP

jaJapanese

ISO-8859-7elGreek

ISO-8859-1deGerman

ISO-8859-1enEnglish

Big5zh (TW)Chinese (Traditional/Taiwan)

CharsetCodeLanguage

Page 111: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Internationalization - Charsets

import java.io.*;import java.text.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

public class HelloJapanReader extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {

res.setContentType("text/plain; charset=Shift_JIS");PrintWriter out = res.getWriter();res.setHeader("Content-Language", "ja");

Locale locale = new Locale("ja", "");DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG,

DateFormat.LONG,locale);

Page 112: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Internationalization - Charsets

out.println("In Japanese:");

try {FileInputStream fis = new FileInputStream(

req.getRealPath("HelloWorld.ISO-2022-JP"));InputStreamReader isr = new InputStreamReader(fis, "ISO-2022-JP");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()));}}

Page 113: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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()

Page 114: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Hosting Server

HttpServlet

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:

Dispatching HTTP requests:

doGet ()doHead ()doDelete ()doOptions ()doPost ()doTrace ()

service ()

HTTP

Client

Page 115: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Server-Side Include (SSI) with Servlets

<HTML>

<HEAD> ... </HEAD>

<BODY>

<SERVLET CODE=Servlet1>

</SERVLET>

...

</BODY>

</HTML>

Servlet1

Request

Response

.shtml fileWeb Server

Page 116: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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>

Page 117: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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));

}}

Page 118: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Chaining

Web

Server

Servlet1Request

Response

Servlet2

Servlet3

Servlet Chaining:

The output from each servlet is passed (piped) as input to

the next servlet.

Page 119: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Filters

http://java.sun.com

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) .

Page 120: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Filters

http://java.sun.com

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.

Page 121: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Session

Session

Session Tracking

Cookies

Page 122: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 123: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Session Tracking

Possible ways for session tracking:

� Cookies

� URL-rewriting

� Hidden form fields

Page 124: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 125: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 126: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Cookies

Benefits of Cookies:� User Identification

� Storing User ID (Username) and Password

� Customize a Web-Site

� Allow client specific (focused) advertising

Page 127: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 128: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 129: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Creating a Cookie

� Constructor for javax.servlet.http.Cookiecreates 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.

Page 130: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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 cookievalue - 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)

Page 131: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Cookie Constructor

ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt

HTTP State Management Mechanism

Status of this Memo

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.

RFC2109

Page 132: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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);

}

...

Page 133: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 134: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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()

Page 135: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 136: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 137: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 138: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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);

}}

}

Page 139: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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>");

}}

Page 140: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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>");

}}

Page 141: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Cookie Example - Netscape

# Netscape HTTP Cookie File

# 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

persistent cookies

all cookies

Page 142: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 143: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 144: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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()

Page 145: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 146: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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);

}

...

Page 147: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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.

Page 148: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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()

Page 149: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 150: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 151: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 152: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HttpSession Example

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);

continued

Page 153: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 154: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

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

Page 155: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HttpSession Example

http://149.222.51.81:8180/home-tomcat/servlet/ShowSession

Page 156: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

HttpSession Example

http://149.222.51.81:8180/home-tomcat/servlet/ShowSession

Page 157: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise

Home directories

URL of the Jakarta-Tomcat Server: 149.222.51.81:8180

Directory for Servlets:

$TOMCAT_WEBAPPS/student-servlet/WEB-INF/classes/eop

URLs (Servlets):http://149.222.51.81:8180/student-servlet/servlet/servlet_name

Access via SSH:

Server-IP: 149.222.51.81, Port: 22User: student-servlet, Passwd: FH_Kiel

Page 158: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise - Update

Compiling Servlets:

Directory Structure (example)

eop

dispert

eop.dispert

package eop.dispert;

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;

// Session Tracking Example

public class ShowSession extends HttpServlet {

javac -target 1.5 ShowSession.java

Servlet API:

servlet-api-5.0.18.jar or servlet-api-2.4.jar

Compile for Java (Tomcat) 5.5

Page 159: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise - Update

Home directories

URL of the Jakarta-Tomcat Server: 149.222.51.81:8180

Directory for Servlets:

$TOMCAT_WEBAPPS/student-servlet/WEB-INF/classes/eop

URLs (Servlets):http://149.222.51.81:8180/student-servlet/servlet/servlet_namehttp://149.222.51.81:8180/

student-servlet/servlet/eop.dispert.ShowSession

Access via SSH:

Server-IP: 149.222.51.81, Port: 22User: student-servlet, Passwd: FH_Kiel

eop.dispert.ShowSession

Info: http://149.222.51.81:8180/student-servlet/

Page 160: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise

Home directories

URL of the Jakarta-Tomcat Server: 149.222.51.81:8180

Directory for JSP:

$TOMCAT_WEBAPPS/student-jsp/jsp/eop

URLs (JSPs):http://149.222.51.81:8180/student-jsp/jsp/eop/name.jsp

Access via SSH:

Server-IP: 149.222.51.81, Port: 22User: student-jsp, Passwd: FH_Kiel

Page 161: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise

Compiling the servlet using the Jakarta Servlet-API:

a) Download the Servlet-API file "servlet.jar".

b) Install the file in the following directory:

"C:\Programme\jdk_dir\jre\lib\ext\"

(with jdk_dir = JDK-directory, e.g. "jdk1.3.0_02").

c) Set the classpath (e.g. using a batch file):

set CLASSPATH=

C:\Programme\jdk_dir\jre\lib\ext\servlet.jar

d) Compile the servlet as usual:

javac filename.java

http://ikarus.e-technik.fh-kiel.de/index.php?id=277

Page 162: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise

User handling during an e-commerce session

Write a Java Servlet that fulfils the following functions:

New customer:

� Welcome this visitor with the message "Welcome to our

shop" (or similar).

� Offer a form (HTML) to register this new customer asking for

the necessary information. Minimum input should be:

� first name, last name and address;

� preferred product line (using the shop); allow at least four

different categories.

� The client sends an HTTP POST request with the complete

set of data from this HTML form.

Page 163: Fachbereich Informatik und Elektrotechnik Java Servletsdispert.international-university.eu/lecture-files/Java_Servlet.pdf · • Standard platform for web applications J2EE platform

Fachbereich Informatik und Elektrotechnik

Programming in Java, Helmut Dispert

Servlet Exercise

Echo the accepted data back to the client in the form of an HTML

table. The user (client) should receive a non-editable version of the

updated information.

Known (old) customer:

� Welcome this visitor with the message

"Welcome 'first name' 'last name' " followed by basic information

about former visits to the shop, like:

� last visit,

� number of visits (since),

� session ID, T

Focused advertising:

� Send to the known visitor customer-oriented advertisements

(banner, e.g. appropriate images that are opened in a separate

small window).