web programming in java java servlet...
TRANSCRIPT
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java
Web Programming in Java
Java Servlet Programming
-
China Jiliang University
Java Web Applications, Helmut Dispert
WorkgroupServer
Java TechnologyEnabled Desktop
MicroEdition
StandardEdition
EnterpriseEdition
High-EndServer
Java TechnologyEnabled Devices
JavaCard
Java 2 Platform Editions
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java 2 Platform
Java 2Enterprise
Edition(J2EE)
Core APIs
Java 2Enterprise
Edition(J2EE)
Core APIs
Java 2StandardEdition(J2SE)
Core APIs
Java 2StandardEdition(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
TVProfileTV
Profile ScreenPhoneProfile
ScreenPhoneProfile
CarProfileCar
Profile
PersonalProfile
PersonalProfile Mobile InformationDevice Profile
Mobile InformationDevice Profile
SmartCard
Profile
SmartCard
Profile
ProfileProfileProfileProfile
ProfileProfileProfileProfileJava 2 Platform, Micro Edition(J2ME) encompasses VMs and coreAPIs specified via Configurations aswell as vertical or market-specificAPIs specified in Profiles.
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java Technology / Range of Devices
-
China Jiliang University
Java Web Applications, Helmut Dispert
J2EE Platform
ToolsTools Application Programming ModelApplication Programming Model
TransactionsTransactions
MessagingMessaging MailMail
Co
nn
ecto
rsC
on
nec
tors
ContainerContainer
EJBsEJBs JSPsJSPs ServletsServlets
Java 2 SDK, Standard EditionJava 2 SDK, Standard EditionCORBACORBA RMIRMI DatabaseDatabase Naming / DirectoryNaming / Directory
Ap
ple
tsA
pp
lets
Java
Bea
ns
Java
Bea
ns
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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.
21 December 2011 - Jakarta Retired
-
China Jiliang University
Java Web Applications, Helmut Dispert
Standard Services and APIs
ServletJava Server Pages
EJB JDBC
Business LogicPresentation
DataAccess
DataClient
JTS/JTA JNDI JavaMail RMI-IIOP JMS
Java 2 Enterprise Edition APIs
-
China Jiliang University
Java Web Applications, Helmut Dispert
What Are Servlets?
Java technology objects which extend the functionality of an HTTP Server.
Comparable to Netscapes NSAPI, Microsofts ISAPI, or Apache Modules
Platform Independent
Server Independent
-
China Jiliang University
Java Web Applications, Helmut Dispert
What Are Servlets?
Web Server
Servlet Engine Container
BrowserURL2
URL1
Servlet2
Servlet1
Multiple requestsIn a single session
Request
Response
Request
Response
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java Servlets
From CGI to Servlet
-
China Jiliang University
Java Web Applications, Helmut Dispert
CGI (Common Gateway Interface) Life Cycle
MainProcess
Request for CGI 1 Child Process for CGI 1
Request for CGI 2 Child Process for CGI 2
Request for CGI 1 Child Process for CGI 1
CGI-basedWeb Server
Example: CGI script written in Perl Each request starts a separate Perl interpreter
-
China Jiliang University
Java Web Applications, Helmut Dispert
MainProcess
Request for CGI 1 Child Process for CGI 1
Request for CGI 2 Child Process for CGI 2
Request for CGI 1
FastCGI-basedWeb Server
FastCGI creates a single persistent processfor each FastCGI program.
FastCGI Life Cycle
-
China Jiliang University
Java Web Applications, Helmut Dispert
Main Process
Request forServer Extension 1 Server Extension 1
Server Extension 2
Web Server with Server Extension API
Request forServer Extension 2
Request forServer Extension 1
Server Extension APIs Life Cycle
-
China Jiliang University
Java Web Applications, Helmut Dispert
Server Extension APIs
Examples: Netscapes NSAPI (WAI) Microsofts 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
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, Helmut Dispert
Main Process
JVM
Java Servlet Life Cycle
Request forServlet 1 Servlet 1
Java Servlet-based Web Server
Servlet 2Request forServlet 2
Request forServlet 1
Thread
Thread
Thread
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Advantages over CGI
Architecturally Faster than CGI Servlets dont 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Free Servlet and JSP engines
Apache Tomcathttp://jakarta.apache.org/tomcat/
SUN JSWDKhttp://java.sun.com/products/servlet/download.html/
IBM WebSphere Application Serverhttp://www.software.ibm.com/webservers
Allaire JRUN
http://www.jrun.com/ Unify ServletExec
http://www.servletexec.com
Gefion Software LiteWebserverhttp://www.gefionsoftware.com/LiteWebServer/
Servlet Engines
http://jakarta.apache.org/tomcat/http://java.sun.com/products/servlet/download.html/http://www.software.ibm.com/webservershttp://www.jrun.com/http://www.servletexec.comhttp://www.gefionsoftware.com/LiteWebServer/
-
China Jiliang University
Java Web Applications, 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
http://host/servlet/ServletName
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Three-tier Architecture
Web ServerContent Level
RelationalDatabaseData and Service Level
PresentationLevel
Clients
Three-tier architecture for application service providers (ASP):focused on accessing information.
-
China Jiliang University
Java Web Applications, Helmut Dispert
Multitier Architecture
Multitier (Internet-based) architecture for application service providers (ASP):focused on accessing application services.
Web ServerContent Level
Clients
PresentationLevel
Relational Databases
Data andService Level
Other Systems
Application LevelApplicationServer
-
China Jiliang University
Java Web Applications, Helmut Dispert
Three-tier servlet model
DBServer
CustomAS
ORB
Java WebServer
Servlet
Servlet
ServletWeb Clients
DB: Database ServerAS: Application ServerORB: Object Request Broker
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java Servlets
DatabaseHTTP-ServerClient
AppletsBrowsers
ServletsServers
-
China Jiliang University
Java Web Applications, Helmut Dispert
Java Servlets
Operating System
Server
Servicee.g. HTTP
Servicee.g. FTP
Servlet
Servlet
Servlet
Servlet
-
China Jiliang University
Java Web Applications, 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).
-
China Jiliang University
Java Web Applications, Helmut Dispert
The Servlet Interface
ServletServlet
GenericServletGenericServlet
HttpServletHttpServlet
MyServletMyServlet Servlet Documentation
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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)
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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.: W3CThe Referer request-header field allows the client to specify, for the server's benefit, the address (URI) of the resource from which the Request-URI was obtained (the "referrer", although the header field is misspelled.)
http://149.222.51.80:8080/
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
HTTP Response
Response Headers: Software running on server
Content type of server response
Date: Sunday 16-June-2013 04:14:12 GMT
Server: JavaWebServer/1.1.1
MIME-Version: 1.0
Content-type: text/html
Content-length:1029
Last-modified: Thursday 9-May-2013 12:15:35 GMT
Example:
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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)
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
HTTP Response Codes
Code Groups:
2xx - Success
3xx - Redirection
4xx - Client error
5xx - Server error
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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
http://www.w3.org/Protocols/http://www.w3.org/Protocols/rfc2616/rfc2616.txt
-
China Jiliang University
Java Web Applications, Helmut Dispert
HTTP Response Codes
Example:
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Generic and HTTP Servlet
Servlet construction:Every servlet must implement the
javax.servlet.Servletinterface.
Possibilities:a) Protocol-independent servlet:
Extend (subclass) the classjavax.servlet.GenericServlet
b) HTTP-Servlet:Extend (subclass) the classjavax.servlet.http.HttpServlet
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Function
Read data sent by the user from HTTP form, applet, or custom HTTP client
Look up HTTP request information Browser capabilities, cookies, requesting host, etc
Generate the results JDBC API, RMI, direct computation
Format the results inside a document HTML, excel, etc.
Send HTTP response parameters MIME types, cookies, compression, etc.
Send the document to the client
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
The Request Object
Encapsulates all information from the client
Allows access to:
request headers
InputStream or Reader
CGI like information
Form data
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Retrieving Information
HttpServletRequest offers several methods to access information about:
initialization parameters
the server
the client
request parameters
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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);
}
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
GenericServlet subclassServer
service()
Generic Servlet
Request
Response
implemented by subclass
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Life-Cycle
Create
Initialize
AvailableFor
Service
UnavailableFor
Service
ServicingRequests
Destroy
Unload
Initialization failed
UnavailableExceptionthrown
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Life-Cycle
Life-Cycle Methods: init (ServletConfig)
service (ServletRequest, ServletResponse) destroy ()
Additional Methods: getServletConfig ()
getServletInfo ()
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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).
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
SampleServlet
public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter out = res.getWriter();
out.println ("Helmut Dispert - Sample Servlet");
out.println ("Fachbereich Informatik und Elektrotechnik");
out.println ("First Sample Servlet");
out.println ("");
out.close();
}
}
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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");
}
ServletConfighttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletConfig.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletConfig.html
-
China Jiliang University
Java Web Applications, Helmut Dispert
ServletConfig- Initialization Information
messageFH-Kiel
repeats5
Initialization with Jakarta-Tomcat: web.xml
(partial listing)
http://java.sun.com/j2ee/dtds/web-app_2_2.dtd
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Context Information
public abstract interface ServletContextDefines a set of methods that a servlet uses to communicate withits 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 databaseinstead. The ServletContext object is contained within the ServletConfigobject, which the Web server provides the servlet when the servlet is initialized.
ServletContexthttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Config Information
public abstract interface ServletConfigA servlet configuration object used by a servlet container used to pass information to a servlet during initialization.
ServletContexthttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
-
China Jiliang University
Java Web Applications, 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!");}
ServletContexthttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html
-
China Jiliang University
Java Web Applications, 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).
-
China Jiliang University
Java Web Applications, 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");}
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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 /..
getReader()Returns a BufferedReader to get the text from the body of the request message.
continued
ServletRequesthttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletRequest.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletRequest.html
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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
http://java.io
-
China Jiliang University
Java Web Applications, Helmut Dispert
HTTP Support
Very common:Servlets that use HTTP(Hypertext Transport Protocol).
Supporting Package: javax.servlet.http
-
China Jiliang University
Java Web Applications, Helmut Dispert
WebServer
HttpServlet subclass
service()
doGet()
doPost()
HTTP Servlet
implemented by subclass
RequestResponse
GET
RequestResponse
POST
-
China Jiliang University
Java Web Applications, Helmut Dispert
WebServer
HttpServlet subclass
service()
doGet()
doPost()
doHead()
HTTP Servlet (HEAD)
GETRequestResponse
POSTRequestResponse
HEADRequestResponse
Body suppressed
HTTP servlet handling a HEAD request:
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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
http://java.io
-
China Jiliang University
Java Web Applications, 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!");}}
-
China Jiliang University
Java Web Applications, 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";
-
China Jiliang University
Java Web Applications, 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("");out.println(title);out.println("");out.println("" + title + "");out.println("
This is output from SimpleServlet.");out.println("");out.close();}
}
-
China Jiliang University
Java Web Applications, 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 ("Helmut Dispert - Request Headers");out.println ("HTTP Request Headers");out.println ("Request Method: " + request.getMethod());out.println ("Request URI: " + request.getRequestURI());out.println ("Request Protocol: " + request.getProtocol() + "
");
out.println ("Header NameHeader Value");
Enumeration headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()){
String headerName = (String) headerNames.nextElement();out.println ("" + headerName + "");out.println ("" + request.getHeader(headerName) + "");
}out.println ("");
}}
deflate: http://tools.ietf.org/html/rfc1951
http://tools.ietf.org/html/rfc1951
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Request Headers
accept-encoding SDCH: Shared Dictionary Compression over HTTP(new HTTP 1.1 extension )
-
China Jiliang University
Java Web Applications, 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
http://149.222.51.81:8180/home-tomcat/servlets/ShowParametersPostForm.htmlhttp://149.222.51.81:8180/home-tomcat/servlets/ShowParametersGetForm.html
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
URI, URL, URN
UR* Terms
URIs
URLs
URNs
http:ftp:...
urn:
-
China Jiliang University
Java Web Applications, Helmut Dispert
URI, URL, URN
Both URLs and URNs are URIs
Expansions:
PURL - Persistent Uniform Resource Locatorhttp://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/
http://purl.oclc.org/http://purl.oclc.org/
-
China Jiliang University
Java Web Applications, Helmut Dispert
Unicode, UCS, and UTF-8
http://www.unicode.org/
http://www.unicode.org/
-
China Jiliang University
Java Web Applications, 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 characterset 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.
http://www.unicode.org/
-
China Jiliang University
Java Web Applications, 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,140encoded characters in Unicode 3.1.The new characters cover several historic scripts, several sets of symbols, and a very large collection of additional CJK ideographs. Unicode 3.1 also features new Unicode character properties, and assignments of property values for the much expanded repertoire of characters.
http://www.unicode.org/unicode/reports/tr27/
-
China Jiliang University
Java Web Applications, 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 xxUCS-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).
-
China Jiliang University
Java Web Applications, Helmut Dispert
ISO-8859-1 (Latin-1)
Unicode\uFFFF
\u0000
ISO-8859-1
#0
#255
(diagrams are not to scale)
\u0000
\u00FF
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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 whichcontain 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
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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("En Espaol");out.println("");out.println(" En Espaol:");out.println(" Hola Mundo!");out.println("");}
}
HTML Character Entities
named character entity
-
China Jiliang University
Java Web Applications, 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("En Espaol");out.println("");out.println(" En Espaol:");out.println(" Hola Mundo!");out.println("");}
}
HTML Character Entities
numbered character entity
-
China Jiliang University
Java Web Applications, 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("En Espa\u00f1ol");out.println("");out.println(" En Espaol:");out.println(" Hola Mundo!");out.println("");}
}
Unicode Escapes
Unicode escape sequence\u00f1
-
China Jiliang University
Java Web Applications, Helmut Dispert
Internationalization - Charsets
PrintWriter uses as the default charsetISO-8859-1 (Latin-1)
Specify alternate charset:
Example: Chinese charset:
res.setContentType ("text/html; charset=gb2312");PrintWriter out = res.getWriter (); // Chinese
-
China Jiliang University
Java Web Applications, 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
Big5, gb2312zh-CNzh (TW)
Chinese (Traditional/Taiwan)
CharsetCodeLanguage
-
China Jiliang University
Java Web Applications, Helmut Dispert
Internationalization - Charsets
import java.io.*;import java.text.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloChinaReader extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/plain; charset=gb2312");PrintWriter out = res.getWriter();res.setHeader("Content-Language", "zh-CN");
Locale locale = new Locale("zh-CN", "");DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG,locale);
-
China Jiliang University
Java Web Applications, Helmut Dispert
Internationalization - Charsets
out.println("In Chinese:");
try {FileInputStream fis = new FileInputStream(
req.getRealPath("HelloWorld.gb2312"));InputStreamReader isr = new InputStreamReader(fis, "gb2312");BufferedReader reader = new BufferedReader(isr);String line = null;while ((line = reader.readLine()) != null) {
out.println(line);}
}catch (FileNotFoundException e) { // No Hello for you}
out.println(full.format(new Date()));}
}
-
China Jiliang University
Java Web Applications, Helmut Dispert
HTTP - continued
HTTP Support ClassesPackage 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()
-
China Jiliang University
Java Web Applications, 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 ()
HTTPClient
-
China Jiliang University
Java Web Applications, Helmut Dispert
Server-Side Include (SSI) with Servlets
...
...
Servlet1
Request
Response
.shtml fileWeb Server
-
China Jiliang University
Java Web Applications, Helmut Dispert
Server-Side Include (SSI) with Servlets
Time Program
Current local time:
Current time in New York:
-
China Jiliang University
Java Web Applications, 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));
}}
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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) .
http://java.sun.com
-
China Jiliang University
Java Web Applications, 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.
http://java.sun.com
-
China Jiliang University
Java Web Applications, Helmut Dispert
Session
SessionSession TrackingCookies
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Session Tracking
Possible ways for session tracking: Cookies
URL-rewriting
Hidden form fields
-
China Jiliang University
Java Web Applications, 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
http://server:port/servlet/Rewrittenhttp://server:port/servlet/Rewritten/123http://server:port/servlet/Rewritten?sessionid=123
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookies
Cookie:Small piece of textual information that is sent from a server toa 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookies
Benefits of Cookies: User Identification Storing User ID (Username) and Password Customize a Web-Site Allow client specific (focused) advertising
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Using Cookies
To send Cookie instantiate Cookie Object set attributes
send the cookie
Get information from Cookie retrieve all cookies from the users request find cookie with specified name
get values from cookies
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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)
-
China Jiliang University
Java Web Applications, 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. ABSTRACTThis 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
ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt
-
China Jiliang University
Java Web Applications, 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);
}
...
-
China Jiliang University
Java Web Applications, 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);
}
...
Cookiehttp://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/Cookie.html
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/Cookie.html
-
China Jiliang University
Java Web Applications, 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()
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/HttpServletRequest.html#getCookies()
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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 Dont depend on cookie being enabled Dont put sensitive information in cookies
http://doubleclick.net
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookie Exampleimport 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);
}}
}
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookie Example - Set Cookiesimport 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookie Example - Show Cookiesimport 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("\n" + "" + "Show Cookies" + "\n" +"\n" + "\n" +" Cookie Name\n" + " Cookie Value");
Cookie[] cookies = request.getCookies();if (cookies != null) {Cookie cookie;for(int i=0; i
-
China Jiliang University
Java Web Applications, 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-P0149.222.51.80:8080 FALSE /dispert/servlet FALSE 1008271810 Persistent-Cookie-1 Cookie-Value-P1149.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
http://www.netscape.com/newsref/std/cookie_spec.htmlhttp://.amazon.comhttp://.sun.com
-
China Jiliang University
Java Web Applications, Helmut Dispert
Cookie Example - Internet Explorer
Persistent-Cookie-0Cookie-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/
0632833920
29459480
3190006880
29459470
*Persistent-Cookie-2
Cookie-Value-P2
149.222.51.80/dispert/servlet/0
63283392029459480
3190006880
29459470
*
filename:helmut dispert@servlet[2].txt
mailto:dispert@servlet[2].txt
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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 users 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()
http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/http/HttpServletRequest.html#getSession()
-
China Jiliang University
Java Web Applications, 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 users 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 others value in the session.
-
China Jiliang University
Java Web Applications, 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 users 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);
}
...
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, 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 sessions invalidate method is used:session.invalidate()
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, Helmut Dispert
HttpSession Example
out.println("\n" + "" + heading + "\n" +"Information on Your Session:\n" +"\n" +"\n" + " Info TypeValue\n" +"\n" + " ID\n" + " " + session.getId() + "\n" +"\n" + " Creation Time\n" +" " + new Date(session.getCreationTime()) + "\n" +"\n" + " Time of Last Access\n" +" " + new Date(session.getLastAccessedTime()) + "\n" +"\n" +" Number of Previous Accesses\n" +" " + accessCount + "\n" +"\n" +"");
continued
-
China Jiliang University
Java Web Applications, 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
http://149.222.51.81:8180/home-tomcat/servlet/ShowSession
-
China Jiliang University
Java Web Applications, Helmut Dispert
HttpSession Example
http://149.222.51.81:8180/home-tomcat/servlet/ShowSession
http://149.222.51.81:8180/home-tomcat/servlet/ShowSession
-
China Jiliang University
Java Web Applications, Helmut Dispert
HttpSession Example
http://149.222.51.81:8180/home-tomcat/servlet/ShowSession
http://149.222.51.81:8180/home-tomcat/servlet/ShowSession
-
China Jiliang University
Java Web Applications, 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_KielTh
is inf
ormati
on is
not fi
nal y
et for
stud
ents
at
China
Jilia
ng Un
iversi
ty
http://149.222.51.81:8180/student-servlet/servlet/servlet_name
-
China Jiliang University
Java Web Applications, 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
-
China Jiliang University
Java Web Applications, 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/
This
inform
ation
is no
t fina
l yet
for st
uden
ts at
China
Jilia
ng Un
iversi
ty
http://149.222.51.81:8180/student-servlet/servlet/servlet_namehttp://149.222.51.81:8180/http://149.222.51.81:8180/student-servlet/
-
China Jiliang University
Java Web Applications, 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
This
inform
ation
is no
t fina
l yet
for st
uden
ts at
China
Jilia
ng Un
iversi
ty
http://149.222.51.81:8180/student-jsp/jsp/eop/name.jsp
-
China Jiliang University
Java Web Applications, 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
This
inform
ation
is no
t fina
l yet
for st
uden
ts at
China
Jilia
ng Un
iversi
ty
http://ikarus.e-technik.fh-kiel.de/index.php?id=277
-
China Jiliang University
Java Web Applications, 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.
-
China Jiliang University
Java Web Applications, Helmut Dispert
Servlet Exercise
Echo the accepted data back to the client in the form of an HTMLtable. 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,
Focused advertising:
Send to the known visitor customer-oriented advertisements (banner, e.g. appropriate images that are opened in a separate small window).
-
China Jiliang University
Java Web Applications, Helmut Dispert
Shopping Cart