Fachbereich Informatik und Elektrotechnik Java Servlets Java Servlet Programming Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java 2 Platform Editions JavaCard Java Technology Enabled Devices Java Technology Enabled Desktop Micro Edition Programming in Java, Helmut Dispert Standard Edition Workgroup Server High-End Server Enterprise Edition Fachbereich Informatik und Elektrotechnik Java 2 Platform Profile Profile Profile Profile Profile Profile Profile Profile Java Java22 Enterprise Enterprise Edition Edition (J2EE) (J2EE) Core CoreAPIs APIs Java Java22 Standard Standard Edition Edition (J2SE) (J2SE) Core CoreAPIs APIs Java 2 Platform, Micro Edition (J2ME) encompasses VMs and core APIs specified via Configurations as well as vertical – or market-specific APIs specified in Profiles. TV TV Profile Profile Screen Screen Car Car Phone Phone Profile Profile Profile Profile Personal Personal Profile Profile Mobile Information Mobile DeviceInformation Profile Device Profile Java Java22Micro MicroEdition EditionCore CoreAPIs APIs Smart Smart Card Card Profile Profile Java JavaProgramming ProgrammingLanguage Language Java JavaHotSpot HotSpot Java JavaVirtual VirtualMaschine Maschine(JVM) (JVM) Programming in Java, Helmut Dispert KVM KVM Card CardVM VM Fachbereich Informatik und Elektrotechnik Java Technology / Range of Devices Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik J2EE Platform EJBs EJBs Application ApplicationProgramming ProgrammingModel Model JSPs JSPs Servlets Servlets Container Container Transactions Transactions Messaging Messaging Mail Mail Java Java22SDK, SDK, Standard StandardEdition Edition CORBA CORBA RMI RMI Programming in Java, Helmut Dispert Database Database Naming Naming/ /Directory Directory Connectors Connectors Applets Applets JavaBeans JavaBeans Tools Tools Fachbereich Informatik und Elektrotechnik 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: IIOP: Remote Method Invocation, JTA: Internet Inter-Orb Protocol, JTS: JMS: Programming in Java, Helmut Dispert Java Transaction API Java Transaction Service API Java Message Service API Fachbereich Informatik und Elektrotechnik Jakarta - Tomcat Jakarta Project The goal of the Jakarta Project is to provide commercialquality server solutions based on the Java Platform that are developed in an open and cooperative fashion. Jakarta is the "overall" project for many subprojects. For example, Tomcat is the Servlet+JSP Engine which is a subproject of the Jakarta Project. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Standard Services and APIs Presentation Business Logic Data Access Servlet Java Server Pages EJB JDBC Data Client JTS/JTA JNDI JavaMail RMI-IIOP Java 2 Enterprise Edition APIs Programming in Java, Helmut Dispert JMS Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik What Are Servlets? Web Server Multiple requests In a single session Servlet Engine Container Request URL1 Servlet 1 URL2 Servlet 2 Response Request Browser Response Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java Servlets From CGI to Servlet Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik CGI (Common Gateway Interface) – Life Cycle Main Process 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-based Web Server Example: CGI script written in Perl Each request starts a separate Perl interpreter Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik FastCGI – Life Cycle Main Process Request for CGI 1 Child Process for CGI 1 Request for CGI 2 Child Process for CGI 2 Request for CGI 1 FastCGI-based Web Server FastCGI creates a single persistent process for each FastCGI program. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Server Extension APIs – Life Cycle Main Process Request for Server Extension 1 Server Extension 1 Request for Server Extension 2 Server Extension 2 Request for Server Extension 1 Web Server with Server Extension API Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java Servlet – Life Cycle Main Process JVM Request for Servlet 1 Thread Servlet 1 Thread Request for Servlet 2 Thread Servlet 2 Request for Servlet 1 Java Servlet-based Web Server Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Three-tier Architecture Presentation Level Clients Content Level Data and Service Level Three-tier architecture for application service providers (ASP): focused on accessing information. Programming in Java, Helmut Dispert Web Server Relational Database Fachbereich Informatik und Elektrotechnik Multitier Architecture Presentation Level Clients Content Level Web Server Application Level Application Server Data and Service Level Relational Databases Other Systems Multitier (Internet-based) architecture for application service providers (ASP): focused on accessing application services. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Three-tier servlet model Java Web Server DB Server Servlet Servlet Servlet Web Clients DB: AS: ORB: Database Server Application Server Object Request Broker Programming in Java, Helmut Dispert Custom AS ORB Fachbereich Informatik und Elektrotechnik Java Servlets Client HTTP-Server Database Browsers Applets Servers Servlets Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java Servlets Operating System Server Service e.g. HTTP Service e.g. FTP Servlet Servlet Servlet Servlet Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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). Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The Servlet Interface Servlet Servlet GenericServlet GenericServlet HttpServlet HttpServlet MyServlet MyServlet Programming in Java, Helmut Dispert Servlet Documentation Fachbereich Informatik und Elektrotechnik Client Interaction Call Client Servlet Servlet receives two objects: 1. ServletRequest: encapsulates the communication from the client to the server. 2. ServletResponse: encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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) Programming in Java, Helmut Dispert Protocol version Fachbereich Informatik und Elektrotechnik 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) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP – Request Request Header Example Host Referer 149.222.51.80:8080 http://149.222.51.80:8080/ dispert/servlets/index.html Accept-Encoding gzip Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* Connection Keep-Alive Accept-Charset iso-8859-1,*,utf-8 User-Agent Mozilla/4.7 [en] (Win98; U) Accept-Language en Ref.: W3C The Referer request-header field allows the client to specify, for the server's benefit, the address (URI) of the resource from which the Request-URI was obtained (the "referrer", although the header field is misspelled.) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP – Response Response Header: Status code (line), status description Examples: HTTP/1.0 200 OK Status code: 200 Request was successful HTTP/1.0 404 Not Found Status code: 404 Requested document was not found Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP – Response Response Headers: Software running on server Content type of server response Example: 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP – Methods GET Method for getting information (e.g. document, DB query result) POST Method for posting (sending) information (e.g. credit card information, DB data) HEAD similar to get, used to receive only the response headers PUT DELETE TRACE OPTIONS Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Response Codes Code Groups: 2xx - Success 3xx - Redirection 4xx - Client error 5xx - Server error Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Response Codes 200-series HTTP response codes indicate that the request was processed without any error conditions. The 200-series responses other than 200 are seldom seen in practice. Code Function Description 200 OK 201 Created Following a POST command, this indicates success, but the text of the response line indicates the URL of the new document. 202 Accepted Request accepted for asynchronous processing. 203 Partial Information Returned information may be cached or private. 204 No Response Used for scripts that don't return a visible result. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Response Codes 300-series response codes indicate that the document requested has moved to some other location, or that the browser is being redirected for some other reason. Code Function Description 301 Moved 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. 302 Found 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. 303 Method Same as found, but a different method may be used to access the document; details about the method are sent in the message body. 304 Not modified Use the local copy if you cached it. Often seen when using the HEAD method, rather than the GET method. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Response Codes 400-series messages indicate that the browser did something wrong. Code Function Description 400 Bad Request Impossible request or syntax error 401 Unauthorized 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. 402 Payment Required Request should be retried with proper charge-to header. 403 Forbidden Authorization will not help 404 Not found A document with that URL doesn't exist. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Response Codes 500-series messages indicate that something went wrong on the server. Usually associated with CGI problems. Code Function Description 500 Internal Error A rather meaningless catch-all message that indicates that the site admin goofed on their CGI program. 501 Not implemented 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. 502 Timed out Not in the HTTP spec, but implemented by some HTTP servers. Hypertext Transfer Protocol -- HTTP/1.1 http://www.w3.org/Protocols/ http://www.w3.org/Protocols/rfc2616/rfc2616.txt Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The Servlet API HTTP Servlets: Servlets use classes and interfaces from the following two packages: javax.servlet supports generic, protocol-independent servlets javax.servlet.http adds HTTP-specific functionality to servlets javax: top-level package name to indicate a standard extension Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Generic and HTTP Servlet Servlet construction: Every servlet must implement the javax.servlet.Servlet interface. Possibilities: a) Protocol-independent servlet: Extend (subclass) the class javax.servlet.GenericServlet b) HTTP-Servlet: Extend (subclass) the class javax.servlet.http.HttpServlet Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The Request Object Encapsulates all information from the client Allows access to: request headers InputStream or Reader CGI like information Form data Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Retrieving Information HttpServletRequest offers several methods to access information about: initialization parameters the server the client request parameters Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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); } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HttpServletResponse HttpServletResponse Object getWriter() returns a Writer for text getOutputStream() returns ServletOutputStream for binary Set header data before above IO set setContentType in header Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Generic Servlet Server GenericServlet subclass Request service() Response implemented by subclass Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Life-Cycle Create Initialize Available For Service Servicing Requests Initialization failed Unavailable For Service Destroy UnavailableException thrown Unload Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Life-Cycle Life-Cycle Methods: init (ServletConfig) service (ServletRequest, ServletResponse) destroy () Additional Methods: getServletConfig () getServletInfo () Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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). Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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"; } Programming in Java, Helmut Dispert continued Fachbereich Informatik und Elektrotechnik 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(); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Initializing Servlets Common in real-life servlets e.g. Initializing database connection pools There are two version of init() Version 1: takes no parameter Version 2: takes a ServletConfig ServletConfig.getInitParameter is used to read initialization parameters init should be used even when no initialization parameters are read Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik ServletConfig- Initialization Information Initialization with Jakarta-Tomcat: web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <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> (partial listing) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Server Context Information Server Context information is made available through the ServletContext object. A servlet can obtain this object by calling the getServletContext() method on the ServletConfig object . This reference should be saved in a private variable within the init() method. private ServletConfig config; public void init (ServletConfig config) { this.config = config; // store config servletContext sc = config.getServletContext (); sc.log ("Started OK!"); } ServletContext http://www.rz.e-technik.fh-kiel.de/~dispert/java/servlet-2_3-fcs-docs/javax/servlet/ServletContext.html Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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). Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Context during Service Request Service requests can contain information in form of name/value parameter pairs as a ServletInputStream or a BufferedReader. This information is available through the ServletRequest object that is passed to the service() method. BufferedReader reader; String param1, param2; public void service {ServletRequest req, ServletResponse res) { reader = req.getReader (); param1 = req.getParameter ("First"); param2 = req.getParameter ("Second"); } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Methods of ServletRequest getAttribute () Returns value of a named attribute for this request. getContentLength() Size of request, if known. getContentType() Returns MIME type of the request message body. getInputStream() Returns an InputStream for reading binary data from the body of the request message. getParameter("name") Returns the value of a request parameter as a String, or null if the parameter does not exist. getParameters ("name") Returns an array of URL-decoded values of all occurrences of name in query string or null if the parameter does not exist. continued Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The javax.servlet package java.io InputStream InputStream javax.servlet ServletInputStream ServletInputStream Servlet Servlet ServletConfig ServletConfig OutputStream OutputStream ServletOutputStream ServletOutputStream ServletContext ServletContext Serializable Serializable ServletRequest ServletRequest java.lang Object Object ServletResponse ServletResponse GenericServlet GenericServlet Exception Exception CLASS CLASS Exception Exception ABSTRACT ABSTRACTCLASS CLASS extends Programming in Java, Helmut Dispert implements SingleThreadModel SingleThreadModel UnavailableException UnavailableException INTERFACE INTERFACE Fachbereich Informatik und Elektrotechnik HTTP Support Very common: Servlets that use HTTP (Hypertext Transport Protocol). Supporting Package: Programming in Java, Helmut Dispert javax.servlet.http Fachbereich Informatik und Elektrotechnik HTTP Servlet Web Server HttpServlet subclass GET Request Response POST Request Response doGet() service() doPost() implemented by subclass Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTTP Servlet (HEAD) HTTP servlet handling a HEAD request: GET Request Response Web Server POST Request Response HEAD Request Response HttpServlet subclass doGet() service() doPost() doHead() Body suppressed Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The javax.http.servlet package javax.http.servlet java.util EventObject EventObject HttpSessionBindingEvent HttpSessionBindingEvent EventListener EventListener HttpSessionBindingListener HttpSessionBindingListener HttpUtils HttpUtils java.io HttpSession HttpSession Cookie Cookie HttpSessionContext HttpSessionContext Serializable Serializable java.lang javax.servlet GenericServlet GenericServlet HttpServlet HttpServlet Object Object Servlet Servlet Cloneable Cloneable CLASS CLASS ServletRequest ServletRequest HttpServletRequest HttpServletRequest ServletResponse ServletResponse HttpServletResponse HttpServletResponse ABSTRACT ABSTRACTCLASS CLASS extends Programming in Java, Helmut Dispert implements INTERFACE INTERFACE Fachbereich Informatik und Elektrotechnik A Simple Servlet – "Hello World" public class HelloServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Hello World!"); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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"; Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik A Simple Servlet public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet – Request Headers import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; 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 out.println out.println out.println out.println ("<HTML><HEAD><TITLE>Helmut Dispert - Request Headers</TITLE></HEAD>"); ("<BODY><H2>HTTP Request Headers</H2>"); ("<BR><B>Request Method:</B> " + request.getMethod()); ("<BR><B>Request URI:</B> " + request.getRequestURI()); ("<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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet – Request Headers accept-encoding SDCH: Shared Dictionary Compression over HTTP (new HTTP 1.1 extension ) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Examples: Form Handling with GET/POST Get Request http://149.222.51.81:8180/home-tomcat/servlets/ShowParametersGetForm.html Post Request http://149.222.51.81:8180/home-tomcat/servlets/ShowParametersPostForm.html Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik URI, URL, URN URI: Uniform Resource Identifier. The generic set of all names/addresses that are short strings that refer to resources. URL: Uniform Resource Locator. An informal term (no longer used in technical specifications) associated with popular URI schemes: http, ftp, mailto, etc. URN: Uniform Resource Name. - An URI that has an institutional commitment to persistence, availability, etc. This sort of URI may also be a URL (example: PURI). - A particular scheme, urn:, specified by RFC2141 and related documents, intended to serve as persistent, locationindependent, resource identifiers. RFC 2396 - Uniform Resource Identifiers (URI): Generic Syntax Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik URI, URL, URN UR* Terms http: ftp: ... URLs URIs Programming in Java, Helmut Dispert urn: URNs Fachbereich Informatik und Elektrotechnik 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/ Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Unicode, UCS, and UTF-8 http://www.unicode.org/ Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik The Unicode Standard The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages of the modern world. In addition, it supports classical and historical texts of many written languages. The Unicode Standard, Version 3.1 The primary feature of Unicode 3.1 is the addition of 44,946 new encoded characters. Together with the 49,194 already existing characters in Unicode 3.0, that comes to a grand total of 94,140 encoded characters in Unicode 3.1. The new characters cover several historic scripts, several sets of symbols, and a very large collection of additional CJK ideographs. Unicode 3.1 also features new Unicode character properties, and assignments of property values for the much expanded repertoire of characters. http://www.unicode.org/unicode/reports/tr27/ Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. ASCII UCS-2 00000000 0xxxxxxx UCS-4 00000000 00000000 00000000 0xxxxxxx 8 8 8 8 ISO 10646 is designed as a 31-bit character set (with possible code positions ranging from \u00000000 to \u7FFFFFFF),. Basic Multilingual Plane (BMP): First 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). Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik ISO-8859-1 (Latin-1) Unicode \uFFFF ISO-8859-1 \u0000 \u00FF #255 \u0000 #0 (diagrams are not to scale) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik ISO-8859-15 (Latin-9) The ISO Latin 9 (ISO 8859-15) character set differs from ISO Latin 1 (ISO 8859-1) character set in a few positions only. The Euro sign € and some national letters used e.g. in French and Finnish have been introduced and some rarely used special characters omitted. Differences between Latin-1 and Latin-9 Position 0xA4 0xA6 0xA8 0xB4 0xB8 0xBC 0xBD 0xBE 8859-1 ¤ ¦ ¨ ´ ¸ ¼ ½ ¾ 8859-15 € Š š Ž ž Œ œ Ÿ Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HTML Character Entities import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter out = res.getWriter(); res.setHeader ("Content-Language", "es"); out.println("<HTML><HEAD><TITLE>En Espa&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>"); named character entity } } Programming in Java, Helmut Dispert &ntilde; Fachbereich Informatik und Elektrotechnik HTML Character Entities import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain2 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter out = res.getWriter(); res.setHeader ("Content-Language", "es"); out.println("<HTML><HEAD><TITLE>En Espa&#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>"); numbered character entity } } Programming in Java, Helmut Dispert &#241; Fachbereich Informatik und Elektrotechnik Unicode Escapes import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloSpain3 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter out = res.getWriter(); res.setHeader ("Content-Language", "es"); out.println("<HTML><HEAD><TITLE>En Espa\u00f1ol</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H2> En Espa&ntilde;ol:</H2>"); out.println("<H2> &iexcl;Hola Mundo!"); out.println("</BODY></HTML>"); Unicode escape sequence } } Programming in Java, Helmut Dispert \u00f1 Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Internationalization - Charsets Language Code Charset Chinese (Traditional/Taiwan) zh (TW) Big5 English en ISO-8859-1 German de ISO-8859-1 Greek el ISO-8859-7 Japanese ja Shift_JIS, ISO-2022-JP, EUC-JP Korean ko EUC-KR Polish pl ISO-8859-2 Russian ru ISO-8859-5, KOI8-R Turkish tr ISO-8859-9 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Internationalization - Charsets import import import import import java.io.*; java.text.*; java.util.*; javax.servlet.*; 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); Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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())); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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() Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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: Hosting Server HTTP Client HttpServlet service () doGet () doHead () doDelete () doOptions () doPost () doTrace () Dispatching HTTP requests: Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Server-Side Include (SSI) with Servlets .shtml file Web Server Request <HTML> <HEAD> ... </HEAD> <BODY> Response <SERVLET CODE=Servlet1> </SERVLET> ... </BODY> </HTML> Programming in Java, Helmut Dispert Servlet1 Fachbereich Informatik und Elektrotechnik 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> Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Server-Side Include (SSI) with Servlets import import import import import java.io.*; java.text.*; javax.servlet.*; javax.servlet.http.*; 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)); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Chaining Web Server Request Servlet1 Servlet2 Response Servlet3 Servlet Chaining: The output from each servlet is passed (piped) as input to the next servlet. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Filters Filter Component: A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters provide the ability to encapsulate recurring tasks in reusable units (modular code). can be used to transform the response from a servlet. A common task for the web application is to format data sent back to the client, e.g. when formats other than just HTML are required (for example, WML) . http://java.sun.com Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Filters Filter Applications: Authentication: blocking requests based on user identity. Logging and auditing: tracking users. Image conversion: scaling, etc. Data compression: to reduce download time. Localization (i.e. targeting particular locales). Transformation of XML content (XSL/T ) Encryption. Tokenizing. Triggering resource access events. Mime-type chaining Caching. http://java.sun.com Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Session Session Session Tracking Cookies Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Session Tracking Possible ways for session tracking: Cookies URL-rewriting Hidden form fields Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Cookies Benefits of Cookies: User Identification Storing User ID (Username) and Password Customize a Web-Site Allow client specific (focused) advertising Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Creating a Cookie Constructor for javax.servlet.http.Cookie creates a cookie with an initial name and value cookie value can later be changed with the setValue method. the value of the cookie can be any String (null value is not guaranteed to work on all browsers). If the servlet returns a response to the user with a Writer, Cookie has to be created before accessing the Writer. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Cookie Constructor public Cookie(java.lang.String name, java.lang.String value) Constructs a cookie with a specified name and value. The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation. The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be changed after creation with the setValue method. By default, cookies are created according to the Netscape cookie specification. The version can be changed with the setVersion method. Parameters: name - a String specifying the name of the cookie value - a String specifying the value of the cookie Throws: java.lang.IllegalArgumentException - if the cookie name contains illegal characters (for example, a comma, space, or semicolon) or it is one of the tokens reserved for use by the cookie protocol See Also: setValue(java.lang.String), setVersion(int) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Cookie Constructor RFC2109 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. ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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); } ... Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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() Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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); } } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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>"); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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>"); } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Cookie Example - Netscape persistent cookies # Netscape HTTP Cookie File all cookies # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. 149.222.51.80:8080 149.222.51.80:8080 149.222.51.80:8080 .amazon.com .sun.com FALSE FALSE FALSE TRUE TRUE /dispert/servlet /dispert/servlet /dispert/servlet / / Programming in Java, Helmut Dispert FALSE FALSE FALSE FALSE FALSE 1008271810 1008271810 1008271810 1008489380 1767225385 Persistent-Cookie-0 Cookie-Value-P0 Persistent-Cookie-1 Cookie-Value-P1 Persistent-Cookie-2 Cookie-Value-P2 session-id-time 1008489600 SUN_ID 149.222.10.12:113901007762577 Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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() Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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); } ... Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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() Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HttpSession Example import import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; // Session Tracking Example public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { continued Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HttpSession Example http://149.222.51.81:8180/home-tomcat/servlet/ShowSession Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik HttpSession Example http://149.222.51.81:8180/home-tomcat/servlet/ShowSession Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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, User: student-servlet, Programming in Java, Helmut Dispert Port: Passwd: 22 FH_Kiel Fachbereich Informatik und Elektrotechnik Servlet Exercise - Update Compiling Servlets: Directory Structure (example) package eop.dispert; import import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; eop dispert eop.dispert // Session Tracking Example public class ShowSession extends HttpServlet { Servlet API: servlet-api-5.0.18.jar or servlet-api-2.4.jar javac -target 1.5 ShowSession.java Compile for Java (Tomcat) 5.5 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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_name http://149.222.51.81:8180/ student-servlet/servlet/eop.dispert.ShowSession eop.dispert.ShowSession Access via SSH: Server-IP: 149.222.51.81, User: student-servlet, Info: Port: Passwd: 22 FH_Kiel http://149.222.51.81:8180/student-servlet/ Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Servlet Exercise Home directories 149.222.51.81:8180 URL of the Jakarta-Tomcat Server: 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, User: student-jsp, Programming in Java, Helmut Dispert Port: Passwd: 22 FH_Kiel Fachbereich Informatik und Elektrotechnik 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 Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik 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). Programming in Java, Helmut Dispert