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

Size: px
Start display at page:

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

Transcription

1 Java Web Programming in Java Java Servlet Programming

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

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

4 Java Technology / Range of Devices

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

6 JAVA 2 EE Standard platform for web applications J2EE platform released December HTML presentation APIs Servlet 2.2 JavaServer Pages : 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

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

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

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

10 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

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

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

13 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

14 Java Servlets From CGI to Servlet

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

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

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

18 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

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

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

21 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

22 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

23 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

24 Free Servlet and JSP engines Apache Tomcat SUN JSWDK IBM WebSphere Application Server Allaire JRUN Unify ServletExec Gefion Software LiteWebserver Servlet Engines

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

26 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

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

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

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

30 Java Servlets Client HTTP-Server Database Browsers Servers Applets Servlets

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

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

33 The Servlet Interface Servlet GenericServlet HttpServlet MyServlet Servlet Documentation

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

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

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

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

38 HTTP Request Request Header Example Host :8080 Referer 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 ,*,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.)

39 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/ OK

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

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

42 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

43 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 ed (security)

44 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

45 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

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

47 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 OK Created Accepted Partial Information No Response Description Following a POST command, this indicates success, but the text of the response line indicates the URL of the new document. Request accepted for asynchronous processing. Returned information may be cached or private. Used for scripts that don't return a visible result.

48 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 Moved Found Method Not modified Description Browsers with link editing capabilities should automatically link to the new reference. The response contains one or more header lines of the form URI: url string CrLf which specify alternative addresses for the object in question. The string is an optional comment field. Same as move, except that linking to the found address doesn't make much sense, since the document URL is expected to change. This is the code that the httpd returns for a cgi script whose output contained a Location: header. Same as found, but a different method may be used to access the document; details about the method are sent in the message body. Use the local copy if you cached it. Often seen when using the HEAD method, rather than the GET method.

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

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

51 HTTP Response Codes Example:

52 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

53 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

54 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

55 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

56 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

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

58 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

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

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

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

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

63 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

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

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

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

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

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

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

70 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

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

72 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

73 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

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

75 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

76 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

77 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

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

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

80 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

81 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

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

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

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

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

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

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

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

89 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!"); } }

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

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

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

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

94 Examples: Form Handling with GET/POST Get Request Post Request

95 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 Uniform Resource Identifiers (URI): Generic Syntax

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

97 URI, URL, URN Both URLs and URNs are URIs Expansions: PURL - Persistent Uniform Resource Locator 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.

98 Unicode, UCS, and UTF-8

99 Unicode, UCS, and UTF-8 UCS and ISO (ISO/IEC ) The international standard ISO 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.

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

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

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

103 ISO (Latin-9) The ISO Latin 9 (ISO ) character set differs from ISO Latin 1 (ISO ) 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 ¼ ½ ¾ Š š Ž ž Œ œ Ÿ

104 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

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

106 UTF-8 Encoding from UCS-4 to UTF-8: UCS-4 range (hex.) UTF-8 octet sequence (binary) F 0xxxxxxx FF 110xxxxx 10xxxxxx FFFF 1110xxxx 10xxxxxx 10xxxxxx F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx FF FFFF xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx FFF FFFF x 10xxxxxx... 10xxxxxx RFC 2279: UTF-8, a transformation format of ISO 10646

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122 Session Session Session Tracking Cookies

123 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

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

125 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

126 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

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

128 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

129 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

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

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

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

133 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); }...

134 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

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

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

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

138 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

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

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

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

142 Cookie Example - Netscape persistent cookies # Netscape HTTP Cookie File all cookies # # This is a generated file! Do not edit :8080 FALSE /dispert/servlet FALSE Persistent-Cookie-0 Cookie-Value-P :8080 FALSE /dispert/servlet FALSE Persistent-Cookie-1 Cookie-Value-P :8080 FALSE /dispert/servlet FALSE Persistent-Cookie-2 Cookie-Value-P2.amazon.com TRUE / FALSE session-id-time sun.com TRUE / FALSE SUN_ID :

143 Cookie Example - Internet Explorer Persistent-Cookie-0 Cookie-Value-P /dispert/servlet/ * Persistent-Cookie-1 Cookie-Value-P /dispert/servlet/ * Persistent-Cookie-2 Cookie-Value-P /dispert/servlet/ * filename: helmut dispert@servlet[2].txt

144 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

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

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

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

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

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

150 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

151 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

152 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

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

154 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

155 HttpSession Example } /** Handle GET and POST requests identically. */ } public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { doget(request, response); }

156 HttpSession Example

157 HttpSession Example

Servlet Fudamentals. Celsina Bignoli

Servlet Fudamentals. Celsina Bignoli Servlet Fudamentals Celsina Bignoli bignolic@smccd.net What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications:

More information

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

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle Introduction Now that the concept of servlet is in place, let s move one step further and understand the basic classes and interfaces that java provides to deal with servlets. Java provides a servlet Application

More information

Java Servlets. Preparing your System

Java Servlets. Preparing your System Java Servlets Preparing to develop servlets Writing and running an Hello World servlet Servlet Life Cycle Methods The Servlet API Loading and Testing Servlets Preparing your System Locate the file jakarta-tomcat-3.3a.zip

More information

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

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently.

More information

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

&' () - #-& -#-!& 2 - % (3 3 !!! + #%!%,)& ! # * +, ! "# # $! " &' ()!"#$$&$'(!!! ($) * + #!,)& - #-& +"- #!(-& #& #$.//0& -#-!& #-$$!& 1+#& 2-2" (3" 3 * * +, - -! #.// HttpServlet $ Servlet 2 $"!4)$5 #& 5 5 6! 0 -.// # 1 7 8 5 9 2 35-4 2 3+ -4 2 36-4 $

More information

Session 8. Introduction to Servlets. Semester Project

Session 8. Introduction to Servlets. Semester Project Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the

More information

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

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web Introduction to Java Servlets James Baldo Jr. SWE 432 Design and Implementation of Software for the Web Web Applications A web application uses enabling technologies to 1. make web site contents dynamic

More information

Servlets and JSP (Java Server Pages)

Servlets and JSP (Java Server Pages) Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight,

More information

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

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Enterprise Edition Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Beans Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 2 Java Bean POJO class : private Attributes public

More information

Advanced Web Technology

Advanced Web Technology Berne University of Applied Sciences Dr. E. Benoist Winter Term 2005-2006 Presentation 1 Presentation of the Course Part Java and the Web Servlet JSP and JSP Deployment The Model View Controler (Java Server

More information

SERVLETS INTERVIEW QUESTIONS

SERVLETS INTERVIEW QUESTIONS SERVLETS INTERVIEW QUESTIONS http://www.tutorialspoint.com/servlets/servlets_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Servlets Interview Questions have been designed especially

More information

UNIT-V. Web Servers: Tomcat Server Installation:

UNIT-V. Web Servers: Tomcat Server Installation: UNIT-V Web Servers: The Web server is meant for keeping Websites. It Stores and transmits web documents (files). It uses the HTTP protocol to connect to other computers and distribute information. Example:

More information

JAVA SERVLET. Server-side Programming INTRODUCTION

JAVA SERVLET. Server-side Programming INTRODUCTION JAVA SERVLET Server-side Programming INTRODUCTION 1 AGENDA Introduction Java Servlet Web/Application Server Servlet Life Cycle Web Application Life Cycle Servlet API Writing Servlet Program Summary 2 INTRODUCTION

More information

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

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http? What are Servlets? Servlets1 Fatemeh Abbasinejad abbasine@cs.ucdavis.edu A program that runs on a web server acting as middle layer between requests coming from a web browser and databases or applications

More information

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Overview Dynamic web content genera2on (thus far) CGI Web server modules Server- side scrip2ng e.g. PHP, ASP, JSP Custom web server Java

More information

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

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets ID2212 Network Programming with Java Lecture 10 Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets Leif Lindbäck, Vladimir Vlassov KTH/ICT/SCS HT 2015

More information

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 Java Servlets Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist Fall Term 2016-17 Introduction HttpServlets Class HttpServletResponse HttpServletRequest Lifecycle Methods Session Handling

More information

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

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web UNIT - 4 Servlet 4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web browser and request the servlet, example

More information

Servlets Basic Operations

Servlets Basic Operations Servlets Basic Operations Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring Overview Preparing to

More information

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

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4 CMPUT 391 Database Management Systems The Basic Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems

More information

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

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON- Ordering Information: Advanced Java 2 Platform How to Program View the complete Table of Contents Read the Preface Download the Code Examples To view all the Deitel products and services available, visit

More information

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

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres sessionx Desarrollo de Aplicaciones en Red José Rafael Rojano Cáceres http://www.uv.mx/rrojano A few more words about Common Gateway Interface 1 2 CGI So originally CGI purpose was to let communicate a

More information

Session 9. Introduction to Servlets. Lecture Objectives

Session 9. Introduction to Servlets. Lecture Objectives Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 10/11/2018 1 Reading & Reference Reading Use the

More information

Module 4: SERVLET and JSP

Module 4: SERVLET and JSP 1.What Is a Servlet? Module 4: SERVLET and JSP A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper

More information

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

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return: Advanced Java Programming Servlets Chris Wong chw@it.uts.edu.au Orginal notes by Dr Wayne Brookes and Threading Copyright UTS 2008 Servlets Servlets-1 Copyright UTS 2008 Servlets Servlets-2 Quick HTTP

More information

Web based Applications, Tomcat and Servlets - Lab 3 -

Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta The Basic Web Server CMPUT 391 Database Management

More information

Servlet Basics. Agenda

Servlet Basics. Agenda Servlet Basics 1 Agenda The basic structure of servlets A simple servlet that generates plain text A servlet that generates HTML Servlets and packages Some utilities that help build HTML The servlet life

More information

JSP. Common patterns

JSP. Common patterns JSP Common patterns Common JSP patterns Page-centric (client-server) CLIENT JSP or Servlet CLIENT Enterprise JavaBeans SERVER DB Common JSP patterns Page-centric 1 (client-server) Page View request response

More information

HTTP and the Dynamic Web

HTTP and the Dynamic Web HTTP and the Dynamic Web How does the Web work? The canonical example in your Web browser Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object

More information

Questions and Answers

Questions and Answers Q.1) Servlet mapping defines A. An association between a URL pattern and a servlet B. An association between a URL pattern and a request page C. An association between a URL pattern and a response page

More information

Advanced Internet Technology Lab # 4 Servlets

Advanced Internet Technology Lab # 4 Servlets Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2011 Advanced Internet Technology Lab # 4 Servlets Eng. Doaa Abu Jabal Advanced Internet Technology Lab # 4 Servlets Objective:

More information

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

Servlets. An extension of a web server runs inside a servlet container Servlets What is a servlet? An extension of a web server runs inside a servlet container A Java class derived from the HttpServlet class A controller in webapplications captures requests can forward requests

More information

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

SSC - Web applications and development Introduction and Java Servlet (I) SSC - Web applications and development Introduction and Java Servlet (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics What will we learn

More information

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

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire

More information

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

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser How does the Web work? The canonical example in your Web browser and the Dynamic Web Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object on a

More information

Chapter 10 Web-based Information Systems

Chapter 10 Web-based Information Systems Prof. Dr.-Ing. Stefan Deßloch AG Heterogene Informationssysteme Geb. 36, Raum 329 Tel. 0631/205 3275 dessloch@informatik.uni-kl.de Chapter 10 Web-based Information Systems Role of the WWW for IS Initial

More information

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

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter. In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter. You can also call request.getparametervalues if the parameter appears more than once,

More information

AJP. CHAPTER 5: SERVLET -20 marks

AJP. CHAPTER 5: SERVLET -20 marks 1) Draw and explain the life cycle of servlet. (Explanation 3 Marks, Diagram -1 Marks) AJP CHAPTER 5: SERVLET -20 marks Ans : Three methods are central to the life cycle of a servlet. These are init( ),

More information

The Structure and Components of

The Structure and Components of Web Applications The Structure and Components of a JEE Web Application Sample Content garth@ggilmour.com The Structure t of a Web Application The application is deployed in a Web Archive A structured jar

More information

CIS 455 / 555: Internet and Web Systems

CIS 455 / 555: Internet and Web Systems 1 Background CIS 455 / 555: Internet and Web Systems Spring, 2010 Assignment 1: Web and Application Servers Milestone 1 due February 3, 2010 Milestone 2 due February 15, 2010 We are all familiar with how

More information

Unit 4 - Servlet. Servlet. Advantage of Servlet

Unit 4 - Servlet. Servlet. Advantage of Servlet Servlet Servlet technology is used to create web application, resides at server side and generates dynamic web page. Before Servlet, CGI (Common Gateway Interface) was popular as a server-side programming

More information

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

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Enterprise Java Introduction Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Course Description This course focuses on developing

More information

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

This course is intended for Java programmers who wish to write programs using many of the advanced Java features. COURSE DESCRIPTION: Advanced Java is a comprehensive study of many advanced Java topics. These include assertions, collection classes, searching and sorting, regular expressions, logging, bit manipulation,

More information

Using Java servlets to generate dynamic WAP content

Using Java servlets to generate dynamic WAP content C H A P T E R 2 4 Using Java servlets to generate dynamic WAP content 24.1 Generating dynamic WAP content 380 24.2 The role of the servlet 381 24.3 Generating output to WAP clients 382 24.4 Invoking a

More information

Oracle Containers for J2EE

Oracle Containers for J2EE Oracle Containers for J2EE Servlet Developer's Guide 10g (10.1.3.1.0) B28959-01 October 2006 Oracle Containers for J2EE Servlet Developer s Guide, 10g (10.1.3.1.0) B28959-01 Copyright 2002, 2006, Oracle.

More information

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

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System 15-415 Database Applications Recitation 6 Project 3: CMUQFlix CMUQ s Movies Recommendation System 1 Project Objective 1. Set up a front-end website with PostgreSQL as the back-end 2. Allow users to login,

More information

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

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets 1. Introduction How do the pages you're reading in your favorite Web browser show up there? When you log into your favorite Web site, how does the Web site know that you're you? And how do Web retailers

More information

Table of Contents. Introduction... xxi

Table of Contents. Introduction... xxi Introduction... xxi Chapter 1: Getting Started with Web Applications in Java... 1 Introduction to Web Applications... 2 Benefits of Web Applications... 5 Technologies used in Web Applications... 5 Describing

More information

Introduction to JSP and Servlets Training 5-days

Introduction to JSP and Servlets Training 5-days QWERTYUIOP{ Introduction to JSP and Servlets Training 5-days Introduction to JSP and Servlets training course develops skills in JavaServer Pages, or JSP, which is the standard means of authoring dynamic

More information

Handling the Client Request: HTTP Request Headers

Handling the Client Request: HTTP Request Headers Handling the Client Request: HTTP Request Headers 1 Agenda Reading HTTP request headers Building a table of all the request headers Understanding the various request headers Reducing download times by

More information

Java4570: Session Tracking using Cookies *

Java4570: Session Tracking using Cookies * OpenStax-CNX module: m48571 1 Java4570: Session Tracking using Cookies * R.G. (Dick) Baldwin This work is produced by OpenStax-CNX and licensed under the Creative Commons Attribution License 4.0 Abstract

More information

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

Lecture 3. HTTP v1.0 application layer protocol. into details. HTTP 1.0: RFC 1945, T. Berners-Lee HTTP 1.1: RFC 2068, 2616 Lecture 3. HTTP v1.0 application layer protocol into details HTTP 1.0: RFC 1945, T. Berners-Lee Lee,, R. Fielding, H. Frystyk, may 1996 HTTP 1.1: RFC 2068, 2616 Ascii protocol uses plain text case sensitive

More information

The Servlet Life Cycle

The Servlet Life Cycle The Servlet Life Cycle What is a servlet? Servlet is a server side component which receives a request from a client, processes the request and sends a content based response back to the client. The Servlet

More information

Chapter 29 Servlets: Bonus for Java Developers 1041

Chapter 29 Servlets: Bonus for Java Developers 1041 Chapter 29 Servlets: Bonus for Java Developers 1041 29 Servlets: Bonus for Java Developers Method Description void init( ServletConfig config ) This method is automatically called once during a servlet

More information

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

Public Draft. Java Servlet Specification v2.3 PUBLIC REVIEW DRAFT 1 PUBLIC REVIEW DRAFT 1 PUBLIC REVIEW DRAFT 1 Java Servlet Specification v2.3 Please send technical comments to: Please send business comments to: servletapi-feedback@eng.sun.com danny.coward@sun.com Public Draft Public Review

More information

Web Based Solutions. Gerry Seidman. IAM Consulting

Web Based Solutions. Gerry Seidman. IAM Consulting Web Based Solutions Gerry Seidman Internet Access Methods seidman@iamx.com http://www.iam-there.com 212-580-2700 IAM Consulting seidman@iamx.com http://www.iamx.com 212-580-2700 (c) IAM Consulting Corp.

More information

Java Servlet Specification, v2.2

Java Servlet Specification, v2.2 Java Servlet Specification, v2.2 Final Release December 17th, 1999 James Duncan Davidson Danny Coward Please send all comments to servletapi-feedback@eng.sun.com. Java Servlet Specification ("Specification")

More information

Java Servlet Specification Version 2.3

Java Servlet Specification Version 2.3 Java Servlet Specification Version 2.3 Please send technical comments to: servletapi-feedback@eng.sun.com Please send business comments to: danny.coward@sun.com Final Release 8/13/01 Danny Coward (danny.coward@sun.com)

More information

ServletConfig Interface

ServletConfig Interface ServletConfig Interface Author : Rajat Categories : Advance Java An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from

More information

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

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. UNIT-VI javax.servlet.http package: The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a Servlet class running under the HTTP protocol

More information

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

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming PSD1B Advance Java Programming Unit : I-V PSD1B- Advance Java Programming 1 UNIT I - SYLLABUS Servlets Client Vs Server Types of Servlets Life Cycle of Servlets Architecture Session Tracking Cookies JDBC

More information

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Advance Java. Configuring and Getting Servlet Init Parameters per servlet Advance Java Understanding Servlets What are Servlet Components? Web Application Architecture Two tier, three tier and N-tier Arch. Client and Server side Components and their relation Introduction to

More information

Java E-Commerce Martin Cooke,

Java E-Commerce Martin Cooke, Java E-Commerce Martin Cooke, 2002 1 Plan The web tier: servlets life cycle Session-management TOMCAT & ANT Applet- communication The servlet life-cycle Notes based largely on Hunter & Crawford (2001)

More information

Application Servers in E-Commerce Applications

Application Servers in E-Commerce Applications Application Servers in E-Commerce Applications Péter Mileff 1, Károly Nehéz 2 1 PhD student, 2 PhD, Department of Information Engineering, University of Miskolc Abstract Nowadays there is a growing demand

More information

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

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes Session 8 Deployment Descriptor 1 Reading Reading and Reference en.wikipedia.org/wiki/http Reference http headers en.wikipedia.org/wiki/list_of_http_headers http status codes en.wikipedia.org/wiki/_status_codes

More information

CSC309: Introduction to Web Programming. Lecture 8

CSC309: Introduction to Web Programming. Lecture 8 CSC309: Introduction to Web Programming Lecture 8 Wael Aboulsaadat Front Layer Web Browser HTTP Request Get http://abc.ca/index.html Web (HTTP) Server HTTP Response .. How

More information

Chapter 10 Servlets and Java Server Pages

Chapter 10 Servlets and Java Server Pages Chapter 10 Servlets and Java Server Pages 10.1 Overview of Servlets A servlet is a Java class designed to be run in the context of a special servlet container An instance of the servlet class is instantiated

More information

Handout 31 Web Design & Development

Handout 31 Web Design & Development Lecture 31 Session Tracking We have discussed the importance of session tracking in the previous handout. Now, we ll discover the basic techniques used for session tracking. Cookies are one of these techniques

More information

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

Fast Track to Java EE 5 with Servlets, JSP & JDBC Duration: 5 days Description Java Enterprise Edition (Java EE 5) is a powerful platform for building web applications. The Java EE platform offers all the advantages of developing in Java plus a comprehensive

More information

Unit 5 JSP (Java Server Pages)

Unit 5 JSP (Java Server Pages) Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. It focuses more on presentation logic

More information

Introdução a Servlets

Introdução a Servlets Introdução a Servlets Sumário 7.1.1.Introdução 7.1.2.Servlet Overview and Architecture 7.1.2.1 Interface Servlet and the Servlet Life Cycle 7.1.2.2 HttpServlet Class 7.1.2.3 HttpServletRequest Interface

More information

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

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved. Borland Application Server Certification Study Guide Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved. Introduction This study guide is designed to walk you through requisite

More information

SERVLET AND JSP FILTERS

SERVLET AND JSP FILTERS SERVLET AND JSP FILTERS FILTERS OVERVIEW Filter basics Accessing the servlet context Using initialization parameters Blocking responses Modifying responses FILTERS: OVERVIEW Associated with any number

More information

CS506 Web Design & Development Final Term Solved MCQs with Reference

CS506 Web Design & Development Final Term Solved MCQs with Reference with Reference I am student in MCS (Virtual University of Pakistan). All the MCQs are solved by me. I followed the Moaaz pattern in Writing and Layout this document. Because many students are familiar

More information

Fast Track to Java EE

Fast Track to Java EE Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This

More information

Servlets Pearson Education, Inc. All rights reserved.

Servlets Pearson Education, Inc. All rights reserved. 1 26 Servlets 2 A fair request should be followed by the deed in silence. Dante Alighieri The longest part of the journey is said to be the passing of the gate. Marcus Terentius Varro If nominated, I will

More information

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

******************************************************************** ******************************************************************** www.techfaq360.com SCWCD Mock Questions : Servlet ******************************************************************** Question No :1

More information

LearningPatterns, Inc. Courseware Student Guide

LearningPatterns, Inc. Courseware Student Guide Fast Track to Servlets and JSP Developer's Workshop LearningPatterns, Inc. Courseware Student Guide This material is copyrighted by LearningPatterns Inc. This content shall not be reproduced, edited, or

More information

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

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22. Answers 1. What is the super interface to all the JDBC Drivers, specify their fully qualified name? a. Java.sql.Driver i. JDBC-ODBC Driver ii. Java-Native API Driver iii. All Java Net Driver iv. Java Native

More information

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

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003 Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

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

Introduction. This course Software Architecture with Java will discuss the following topics: Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

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

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers Session 9 Deployment Descriptor Http 1 Reading Reading and Reference en.wikipedia.org/wiki/http Reference http headers en.wikipedia.org/wiki/list_of_http_headers http status codes en.wikipedia.org/wiki/http_status_codes

More information

Problems in Scaling an Application Client

Problems in Scaling an Application Client J2EE What now? At this point, you understand how to design servers and how to design clients Where do you draw the line? What are issues in complex enterprise platform? How many servers? How many forms

More information

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

JAVA SERVLETS INTRODUCTION SERVLETS SHRI GURU RAM RAI INSTITUTE OF TECHNOLOGY & SCIENCE, DEHRADUN JAVA SERVLETS INTRODUCTION Java servlets are programs that run on web server. Java applets are programs that are embedded into the web pages. When browser loads the web page the applets byte code is downloaded

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Java Server Pages (JSP) Dr. Basem Suleiman Service Oriented Computing Group, CSE, UNSW Australia Semester 1, 2016, Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2442

More information

Deccansoft Software Services. J2EE Syllabus

Deccansoft Software Services. J2EE Syllabus Overview: Java is a language and J2EE is a platform which implements java language. J2EE standard for Java 2 Enterprise Edition. Core Java and advanced java are the standard editions of java whereas J2EE

More information

Introduction to Web applications with Java Technology 3- Servlets

Introduction to Web applications with Java Technology 3- Servlets Introduction to Web applications with Java Technology 3- Servlets Juan M. Gimeno, Josep M. Ribó January, 2008 Contents Introduction to web applications with Java technology 1. Introduction. 2. HTTP protocol

More information

13. Databases on the Web

13. Databases on the Web 13. Databases on the Web Requirements for Web-DBMS Integration The ability to access valuable corporate data in a secure manner Support for session and application-based authentication The ability to interface

More information

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

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

web.xml Deployment Descriptor Elements

web.xml Deployment Descriptor Elements APPENDIX A web.xml Deployment Descriptor s The following sections describe the deployment descriptor elements defined in the web.xml schema under the root element . With Java EE annotations, the

More information

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

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil Servlet And JSP, Government Polytechnic, Ahmednagar Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To write servlet for cookies and session

More information

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

Java Card 3 Platform. Peter Allenbach Sun Microsystems, Inc. Java Card 3 Platform Peter Allenbach Sun Microsystems, Inc. Agenda From plastic to Java Card 3.0 Things to know about Java Card 3.0 Introducing Java Card 3.0 Java Card 3.0 vs. Java SE Java Card 3.0 vs.

More information

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

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response: Managing Cookies Cookies Cookies are a general mechanism which server side applications can use to both store and retrieve information on the client side Servers send cookies in the HTTP response and browsers

More information

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

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format. J2EE Development Detail: Audience www.peaksolutions.com/ittraining Java developers, web page designers and other professionals that will be designing, developing and implementing web applications using

More information

Advanced Java Programming

Advanced Java Programming Advanced Java Programming Length: 4 days Description: This course presents several advanced topics of the Java programming language, including Servlets, Object Serialization and Enterprise JavaBeans. In

More information

Unit-4: Servlet Sessions:

Unit-4: Servlet Sessions: 4.1 What Is Session Tracking? Unit-4: Servlet Sessions: Session tracking is the capability of a server to maintain the current state of a single client s sequential requests. Session simply means a particular

More information

Distributed Systems 1

Distributed Systems 1 95-702 Distributed Systems 1 Joe Intro Syllabus highlights 95-702 Distributed Systems 2 Understand the HTTP application protocol Request and response messages Methods / safety / idempotence Understand

More information

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

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Welcome To PhillyJUG 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Web Development With The Struts API Tom Janofsky Outline Background

More information

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

index_ qxd 7/18/02 11:48 AM Page 259 Index index_259-265.qxd 7/18/02 11:48 AM Page 259 Index acceptance testing, 222 activity definition, 249 key concept in RUP, 40 Actor artifact analysis and iterative development, 98 described, 97 136 in the

More information

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Session 20 Data Sharing Session 20 Data Sharing & Cookies Session 20 Data Sharing & Cookies 1 Reading Shared scopes Java EE 7 Tutorial Section 17.3 Reference http state management www.ietf.org/rfc/rfc2965.txt Cookies Reading & Reference en.wikipedia.org/wiki/http_cookie

More information