Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Java Servlets Rochester Java Users Group January 16th, 2002 Tom Bullinger

Similar presentations

Presentation on theme: "Introduction to Java Servlets Rochester Java Users Group January 16th, 2002 Tom Bullinger"— Presentation transcript:

1 Introduction to Java Servlets Rochester Java Users Group January 16th, 2002 Tom Bullinger

2 Tom Bullinger Agenda HTTP Web Architecture Applets Servlets Source / Demo References

3 Tom Bullinger ArchWise, LLC A professional services firm specializing in software architecture. We provide technical architecture solutions that are elegant as well as functional, and are designed to meet the ongoing needs of the business as well as the marketplace. We help our clients produce the right solution on time and on budget. Member WWISA (

4 Tom Bullinger ArchWise Software Architecture Map Cover Story Business Architecture Identity Vision Statement Goals Principles To be the best… To provide … Our core … Partner with… Architecture of Change Results Key Events Projects Organization Changes Learnings Key Hires Market Architecture Technical Architecture Execution Test Logical Arch. Design Code Release Market Map User Stories Logical Architecture Conceptual Architecture UMLInterfacesUse Cases Conceptual Precise Abstract Meticulous Start with: Business Plan Start with: Architecture of Change Start with: Conceptual Architecture Start with: Logical Architecture CRM ERP Supply Chain Road Map STAGES/TASKS Press Release Press Release Product Release Product Upgrade MISSION Q1 ‘02Q2 ‘02 Stakeholder Profile Context Content Area Menu Brand Tools/Status Business Goals System Goals Magazine Cover Brain Storms Business Image Sidebars Quotes Human Interest Lead Story

5 Tom Bullinger HTTP Hypertext Transfer Protocol is: The primary protocol for Internet communication Text based messages through sockets  Although payload may not be text Used to exchange resources  Files, video, audio, forms, graphics, etc. A Client / Server protocol (2-tier architecture)  Client opens a connection to a server  Client sends a request message to the server  Server sends a response message  Server closes the connection A stateless protocol  Request  Response

6 Tom Bullinger HTTP Request Initial request line has 3 components: Method name Path to requested Resource HTTP version number GET /web/index.html HTTP/1.0

7 Tom Bullinger HTTP Response Initial response line (or status line) has 3 components: HTTP version number Response Status Code Reason Phrase HTTP/1.0 404 Not Found HTTP/1.0 200 OK HTTP/1.0 500 Server Error

8 Tom Bullinger HTTP Headers Headers are mostly optional, and include supporting information for the request or response messages Consists of 2 parts: Header name Value From: User-Agent: Mozilla/3.0Gold From: User-Agent: Mozilla/3.0Gold (Request) Server: Apache/1.2b3-dev Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT Content-type: text/html Content-length: 47 Server: Apache/1.2b3-dev Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT Content-type: text/html Content-length: 47 ( Response )

9 Tom Bullinger HTTP Example GET /path/file.html HTTP/1.0 From: User-Agent: Mozilla/3.0Gold [blank line] GET /path/file.html HTTP/1.0 From: User-Agent: Mozilla/3.0Gold [blank line] (Request) HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 Use Servlets!. [blank line] HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354 Use Servlets!. [blank line] (Response)

10 Tom Bullinger HTTP Methods GET Requests a resource from the server Data is URL-encoded and appended to URL HEAD Like GET, but returns the header only, not the resource POST Like GET, but data is URL-encoded in message body  Extra header lines  Message body (data) Typically a script or program invocation Response is typically created dynamically

11 Tom Bullinger URL Encoded Data (Key/Value) HTML form data is usually URL-encoded to package it in a GET or POST submission. In a nutshell, here's how you URL-encode the name-value: 1. Convert all "unsafe" characters in the names and values to "%xx", where "xx" is the ascii value of the character, in hex. "Unsafe" characters include =, &, %, +, non-printable characters, and any others you want to encode 2. Change all spaces to plusses. 3. String the names and values together with = and & name1=value1&name2=value2&name3=value3

12 Tom Bullinger Web Browser Architecture Client (browser) User Server (web server) Files

13 Tom Bullinger Typical Interaction :Browser User :ServerHTML:File URL GET URL HTTP/1.0 Decode(URL) Read() HTTP/1.0 200 OK… Display(HTML)

14 Tom Bullinger Problems? Where is the work done? Is this scalable? Is this flexible? What about dynamic content?

15 Tom Bullinger Applets Extends Browser capability Implemented in Java Downloaded from server to client Interpreted by Browser (or plug-in) Embedded in static web pages (HTML) Provides rich visual functionality Limited capability on the local machine Cannot access file system Cannot access non-home IP addresses Cannot access underlying OS

16 Tom Bullinger Applet Architecture Client (browser) User Server (web server) Files Client (applet) Custom Backend Files

17 Tom Bullinger Typical Interaction :Browser User :ServerHTML:File URL GET URL HTTP/1.0 decode(URL) :Applet read(…) HTML Applet init() start() paint()

18 Tom Bullinger Applet Limitations No persistence mechanism Client-side implementation Requires custom backend for server-side Practical limit to size (due to download) Limited functionality on client (Actually limited by security manager, could be replaced if desired) Others?

19 Tom Bullinger Servlets Implemented in Java Extends the request / response capability of the server Handles client HTTP requests No user interface component Compatible with many servers Server / container manages lifecycle May be reentrant

20 Tom Bullinger Lineage of a Servlet Servlet Generic Servlet HttpServlet Custom Servlet (Interface) (Abstract base class) (Default implementation) (user-supplied behavior)

21 Tom Bullinger Methods of interest doGet - implements HTTP GET requests doPost - implements HTTP POST requests doPut - implements HTTP PUT requests doDelete - for HTTP DELETE requests init and destroy - manage resources that are held for the life of the servlet getServletInfo - provides information about the servlet

22 Tom Bullinger Other Methods service - Server entry point, dispatches to doXXX methods doTrace - implements HTTP TRACE requests doOptions - implements HTTP OPTIONS requests

23 Tom Bullinger Servlet Data interface Two interfaces are utilized in the client / servlet relationship: ServletRequest - encapsulates communication from the client to the server ServletResponse - encapsulates communication from the servlet back to the client Instances provided by the framework ServletRequest HttpServletRequest ServletResponse HttpServletResponse

24 Tom Bullinger A Simple Servlet public class SimpleServlet extends HttpServlet { 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(" "); out.println(title); out.println(" "); out.println(" " + title + " "); out.println(" This is output from SimpleServlet."); out.println(" "); out.close(); } }

25 Tom Bullinger Servlet Architecture Client (browser) User Server (web server) Files Servlet Files

26 Tom Bullinger Typical Interaction :Browser User :Server:Servlet URL GET URL HTTP/1.0 decode(URL) HTTP/1.0 200 OK… Display(HTML) service(rq, rs) rq:Requestrs:Response doGet(rq, rs) write(…) Behavior goes here

27 Tom Bullinger Handling requests from the Client HttpServletRequest Encapsulates the data provided by the client Provides several methods for accessing the data:  getParameter(String name) - returns the value of the specified parameter  getParameterValues(String name) - returns an array of strings of parameter values  getParameterNames( ) - returns an enumeration of names  getQueryString( ) - provide raw data from a GET request  getReader( ) - for reading raw text data from the request  getInputStream( ) - for reading raw binary data from the request

28 Tom Bullinger Responding to Clients HttpServletResponse Encapsulates the data provided to the client Provides several methods for setting the data:  setContentType(String type) - sets the header value for content type  getWriter( ) - provides a Writer for adding data to the response  getOutputStream( ) - for writing raw binary data to the response

29 Tom Bullinger doGet and doPost Pattern Read input data from the Request object Get the output writer from the Response object Setup the header data Perform the necessary processing Database access Calculations Input/Output Write the HTML to the response object

30 Tom Bullinger Source Template public void doGet/doPost (HttpServletRequest request, HttpServletResponse response) … { // set content-type header before accessing the Writer response.setContentType("text/html"); // get the writer PrintWriter out = response.getWriter(); // extract data from the request String name = request.getParameter(“FirstName"); // perform required processing … // write the output to the writer (in HTML) … // cleanup out.close(); }

31 Tom Bullinger Lifecycle of a servlet The container: Creates and initializes the Servlet Handles zero or more servic calls from clients Destroys the Servlet and garbage collects it Servlets persist between service calls Memory footprint is reduced Dynamic resources are held open  database handles  Socket connections Lifecycle overhead is eliminated Each client gets a thread

32 Tom Bullinger When should you use a servlet? For dynamic web content Allows easy connection to database for persistence mechanism For stateful protocols Servlet session maintains state For server performance Servlets are loaded once, reentrant thereafter For embedded web servers Web-enabled appliances

33 Tom Bullinger Advantages of Servlets Portability - “write once, serve anywhere” Unlike applets, only need to be tested on the server No complex GUI Power Full power of Java is available  JDBC  RMI  J2EE  CORBA Bridge  EJB  JTS  JMS  JNDI Support for third-party tools

34 Tom Bullinger More Advantages Efficiency Once loaded, remains loaded Multiple concurrent requests handled by threads Maintains state across invocations (if appropriate) Safety Java type-safety Java memory management Java exception handling Java security manager

35 Tom Bullinger More Advantages Elegance Clean, object-oriented, modular code Base classes provide routine functionality  Programming by difference Integration As a server extension, leverages server capability  File paths  Logging  Authorization  MIME type mapping Session tracking  Overlays state on HTTP protocol

36 Tom Bullinger More Advantages Extensible Built-in support for HTTP Servlets Others can be created Can create HTML Can work with XML / XSLT

37 Tom Bullinger Deploying Servlets In HTML Specify servlet URL in ACTION tag Specify servlet URL in HREF tag Specify servlet URL directly

38 Tom Bullinger Servlet Containers Tomcat Standalone HTTP / servlet container HTTP server extension / servlet container J2EE Servlet container EJB container JMS JNDI JTA JAXP JDBC Etc.

39 Tom Bullinger Demo / Examples Let’s look at some running Servlets

40 Tom Bullinger References Java Servlet Programming - Jason Hunter with William Crawford Copyright 2001, 1998 O’Reilly & Associates The Internet Big Picture - Russ Haynal

Download ppt "Introduction to Java Servlets Rochester Java Users Group January 16th, 2002 Tom Bullinger"

Similar presentations

Ads by Google