7735978-Servlets and the Java Web Server

download 7735978-Servlets and the Java Web Server

of 127

Transcript of 7735978-Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    1/127

    11/04/08 Copyright 1997-8, Purple Te 1

    Servlets and the Java Web Server

    Server-Side Programming Made Easy

    Written by Alex Chaffee ([email protected])Contents Copyright (c) 1998 Purple Technology, Inc.

  • 8/8/2019 7735978-Servlets and the Java Web Server

    2/127

    Copyright 1997-8, Purple Technology Inc. 2

    Servlets and the Java Web Server

    11/04/08

    Course OutlineServlet OverviewServlet OverviewUsing ServletsUsing Servlets

    Writing ServletsWriting ServletsSaving StateSaving StateJava Web Server FeaturesJava Web Server Features

    Appendix: CGI TutorialAppendix: CGI TutorialAppendix: FAQAppendix: FAQ

    Inside the Exercises Handout

  • 8/8/2019 7735978-Servlets and the Java Web Server

    3/127

    11/04/08 Copyright 1997-8, Purple Te 3

    Section I

    Servlet OverviewServlet Overview

  • 8/8/2019 7735978-Servlets and the Java Web Server

    4/127

    Copyright 1997-8, Purple Technology Inc. 4

    Servlets and the Java Web Server

    11/04/08

    What Is A ServletA Java objectA Java objectPlug-in for a web server Plug-in for a web server

    Replacement for CGI scriptsReplacement for CGI scriptsCan also be used to extend server as a plug-in

    Full power of JavaFull power of JavaPlatform-independentDatabase accessFun to write

  • 8/8/2019 7735978-Servlets and the Java Web Server

    5/127

    Copyright 1997-8, Purple Technology Inc. 5

    Servlets and the Java Web Server

    11/04/08

    Server/Service/Servletserver - a process running on a hostserver - a process running on a hostmachinemachine

    Apache, Java Web Server

    service - a protocol running on a portservice - a protocol running on a portHTTP, FTP

    servlet - a module running inside a serviceservlet - a module running inside a servicePhoneServlet

  • 8/8/2019 7735978-Servlets and the Java Web Server

    6/127

    Copyright 1997-8, Purple Technology Inc. 6

    Servlets and the Java Web Server

    11/04/08

    Servlet/Service/Server Diagram

    (diagram from Java Web Server tutorial)(diagram from Java Web Server tutorial)

  • 8/8/2019 7735978-Servlets and the Java Web Server

    7/127

    Copyright 1997-8, Purple Technology Inc. 7

    Servlets and the Java Web Server

    11/04/08

    Servlets vs. AppletsServlets have no GUIServlets have no GUIServer-side, not client-sideServer-side, not client-side

    Different security modelDifferent security modelInstalled, not downloadedInstalled, not downloaded

    But you can download remote servlets too

    Consistent server-side VMConsistent server-side VMMuch easier to test

  • 8/8/2019 7735978-Servlets and the Java Web Server

    8/127

    Copyright 1997-8, Purple Technology Inc. 8

    Servlets and the Java Web Server

    11/04/08

    Servlets vs. CGI"performance, flexibility, portability, and"performance, flexibility, portability, andsecurity" (whitepaper)security" (whitepaper)

    Faster and Leaner Faster and Leaner

    No fork-process like Perl No need to initialize for each requestOnly lightweight thread context switching

    Built-in multithreading

  • 8/8/2019 7735978-Servlets and the Java Web Server

    9/127

    Copyright 1997-8, Purple Technology Inc. 9

    Servlets and the Java Web Server

    11/04/08

    Servlets vs. CGI (Cont.)Easy to manage stateEasy to manage state

    share data across successive requestsshare data between concurrent requestsuse hidden fields, cookies, or sessions

    Write once, run anywhereWrite once, run anywhereIt's easy to write unportable Perl

    Servlets have standard APISupports all methodsSupports all methods

    GET, POST, PUT, DELETE, et al.

  • 8/8/2019 7735978-Servlets and the Java Web Server

    10/127

    Copyright 1997-8, Purple Technology Inc. 10

    Servlets and the Java Web Server

    11/04/08

    Servlets vs. FastCGIFastCGI sends multiple requests to a singleFastCGI sends multiple requests to a singleseparate processseparate process

    requires process context switch

    Servlets send multiple requests to multiple threadsServlets send multiple requests to multiple threadsin same processin same process

    requires lightweight thread context switch

    (Also applies to ISAPI)(Also applies to ISAPI)Nice diagram in White Paper Nice diagram in White Paper Servlets also automatically take advantage of Servlets also automatically take advantage of multiprocessorsmultiprocessors

    if the underlying JVM does

  • 8/8/2019 7735978-Servlets and the Java Web Server

    11/127

    Copyright 1997-8, Purple Technology Inc. 11

    Servlets and the Java Web Server

    11/04/08

    Supported ServersJava Web Server Java Web Server ApacheApache

    NetscapeNetscapeMany others (see web site)Many others (see web site)Servlet EnginesServlet Engines

    IBM's ServletExpressLive Softwares JRun

  • 8/8/2019 7735978-Servlets and the Java Web Server

    12/127

    Copyright 1997-8, Purple Technology Inc. 12

    Servlets and the Java Web Server

    11/04/08

    Servlet SecurityTrusted Servlets (full access)Trusted Servlets (full access)

    JWS InternalLocal (in the "servlets" directory)

    Servlet SandboxServlet SandboxSigned Network Servlets (full access)Unsigned Network Servlets (limited access)

  • 8/8/2019 7735978-Servlets and the Java Web Server

    13/127

    Copyright 1997-8, Purple Technology Inc. 13

    Servlets and the Java Web Server

    11/04/08

    Servlet Security: ImplicationsIT managers can sign servlets for use inIT managers can sign servlets for use intheir organizationtheir organizationISPs can allow users to run servletsISPs can allow users to run servlets

    less of a security hole than CGI scripts, since Java issafe and secure (at least more so than C or Perl)still allows denial-of-service attacks

    Network servlets are possibleNetwork servlets are possiblechaining / proxyingallows agentscommon servlet repository for multiple servers

    one place to install updates

  • 8/8/2019 7735978-Servlets and the Java Web Server

    14/127

    Copyright 1997-8, Purple Technology Inc. 14

    Servlets and the Java Web Server

    11/04/08

    Servlet Security: ProblemsToo simplisticToo simplistic

    All or nothing

    Should allow ACLs for particular signersShould allow ACLs for particular signers

    They claim it will in a future version

    Should get better with 1.2 security modelShould get better with 1.2 security modelFiner-grained access control

  • 8/8/2019 7735978-Servlets and the Java Web Server

    15/127

    Copyright 1997-8, Purple Technology Inc. 15

    Servlets and the Java Web Server

    11/04/08

    Servlet Client SecurityJava Web Server Java Web Server

    Allows Access Control Lists for clientsSupports HTTP authenticationSupports Digest Authentication

    Other Web ServersOther Web ServersUsually support HTTP authentication

    May have other security features

  • 8/8/2019 7735978-Servlets and the Java Web Server

    16/127

    Copyright 1997-8, Purple Technology Inc. 16

    Servlets and the Java Web Server

    11/04/08

    SSL in JWSIt worksIt worksExtra $$Extra $$

    https: supportedhttps: supportedDigest Authentication supportedDigest Authentication supported

    SSL 3 (client certificates) required

  • 8/8/2019 7735978-Servlets and the Java Web Server

    17/127

    Copyright 1997-8, Purple Technology Inc. 17

    Servlets and the Java Web Server

    11/04/08

    Authenticating the users identityHTTP AuthenticationHTTP Authentication

    Username/password sent to server on every request(like cookies)Very light encryption (uuencode)

    Digest AuthenticationDigest AuthenticationCryptographic handshaking between client and

    server Very good encryption Not supported by all servers/browsers

  • 8/8/2019 7735978-Servlets and the Java Web Server

    18/127

    Copyright 1997-8, Purple Technology Inc. 18

    Servlets and the Java Web Server

    11/04/08

    User Authentication Methodsrequest.getRemoteUser()request.getRemoteUser()

    returns username

    request.getAuthType()request.getAuthType()

    HTTP or Digest

    request.getScheme()request.getScheme()http or https

  • 8/8/2019 7735978-Servlets and the Java Web Server

    19/127

    Copyright 1997-8, Purple Technology Inc. 19

    Servlets and the Java Web Server

    11/04/08

    API AvailabilityStandard Java Extension APIStandard Java Extension API

    From white paper: "This means that while it is not part of the core Java framework which must always be part of all products bearing the Java brand, it will be made available with such products by their vendors as an add-on package."

    package javax.servlet.*, javax.servlet.http.*package javax.servlet.*, javax.servlet.http.*

  • 8/8/2019 7735978-Servlets and the Java Web Server

    20/127

    Copyright 1997-8, Purple Technology Inc. 20

    Servlets and the Java Web Server

    11/04/08

    Servlet Architectures:Three-tier system

    Tier 1: ClientTier 1: ClientHTML browser Java client

    Tier 2: ServletsTier 2: Servletsembody business logicsecure, robust

    Tier 3: Data SourcesTier 3: Data SourcesJava can talk to SQL, CORBA, OODB, File system,etc. etc.

  • 8/8/2019 7735978-Servlets and the Java Web Server

    21/127

    Copyright 1997-8, Purple Technology Inc. 21

    Servlets and the Java Web Server

    11/04/08

    Servlet Architectures: N-tier system

    Tier 1: HTML Browser Tier 1: HTML Browser Tier 2: ServletTier 2: Servlet

    User interface

    Tier 3: EJB/CORBA/RMI ObjectsTier 3: EJB/CORBA/RMI ObjectsBusiness logic

    Tier 4: Other Servers (e.g. RDBMS)Tier 4: Other Servers (e.g. RDBMS)Data storage

  • 8/8/2019 7735978-Servlets and the Java Web Server

    22/127

    Copyright 1997-8, Purple Technology Inc. 22

    Servlets and the Java Web Server

    11/04/08

    Servlet Architectures: Web Publishing

    SSI ServletsSSI ServletsJSP ServletsJSP Servlets

    Best to keep business logic inside Java objectsKeep the JSP light so designers dont get scared

    Chaining servletsChaining servletsMultiple serversMultiple servers

    data gathering, collecting, serving, load balancing,etc.

  • 8/8/2019 7735978-Servlets and the Java Web Server

    23/127

    11/04/08 Copyright 1997-8, Purple Te 23

    Section II

    Using ServletsUsing Servlets

  • 8/8/2019 7735978-Servlets and the Java Web Server

    24/127

    Copyright 1997-8, Purple Technology Inc. 24

    Servlets and the Java Web Server

    11/04/08

    Loading ServletsFrom CLASSPATHFrom CLASSPATH

    includes /classes/ on JWS

    From /servlets/ directoryFrom /servlets/ directorynot in classpathservlets can be added or recompiled inside a runningserver

    class.initArgs fileFrom remote codebaseFrom remote codebase

    specified by URL

  • 8/8/2019 7735978-Servlets and the Java Web Server

    25/127

    Copyright 1997-8, Purple Technology Inc. 25

    Servlets and the Java Web Server

    11/04/08

    Remote ServletsThree ways to configureThree ways to configure

    configure with Administration Toolinvoke inside a server-side includeconfigure inside a servlet chain

    Loaded in a Servlet SandboxLoaded in a Servlet Sandboxmore later

  • 8/8/2019 7735978-Servlets and the Java Web Server

    26/127

    Copyright 1997-8, Purple Technology Inc. 26

    Servlets and the Java Web Server

    11/04/08

    What's In A NameA servlet's name is its class nameA servlet's name is its class name

    if it's in the servlets directory

    Or, you can assign it a name in the "AddOr, you can assign it a name in the "AddServlet" admin toolServlet" admin tool

    maps code word to servlet class

    Name is usually a single wordName is usually a single word possibly with a package name and dotsno other punctuation

  • 8/8/2019 7735978-Servlets and the Java Web Server

    27/127

    Copyright 1997-8, Purple Technology Inc. 27

    Servlets and the Java Web Server

    11/04/08

    Standard ServletsDateServletDateServlet

    echoes current date/timeEchoServletEchoServlet

    echoes CGI parameters (good for testing)MailServletMailServlet

    sends email in response to a CGI formRedirectServletRedirectServlet

    used by server to manage HTTP redirects

    SessionServletSessionServletused by server to manage sessionsMany more...Many more...

  • 8/8/2019 7735978-Servlets and the Java Web Server

    28/127

    Copyright 1997-8, Purple Technology Inc. 28

    Servlets and the Java Web Server

    11/04/08

    Server-side Includes (SSI)Must be in a file named .shtml or .jspMust be in a file named .shtml or .jsp

    can change this with Admin Tool

    Normal SSINormal SSI

    Servlet SSIServlet SSI

  • 8/8/2019 7735978-Servlets and the Java Web Server

    29/127

    Copyright 1997-8, Purple Technology Inc. 29

    Servlets and the Java Web Server

    11/04/08

    SSI Detailspass init parameters in servlet tagpass init parameters in servlet tagpass servlet parameters in param tagspass servlet parameters in param tags

    can specify codebase in servlet tagcan specify codebase in servlet tage.g.e.g.

  • 8/8/2019 7735978-Servlets and the Java Web Server

    30/127

    Copyright 1997-8, Purple Technology Inc. 30

    Servlets and the Java Web Server

    11/04/08

    URL invocationDirectly from browser as URLDirectly from browser as URL

    http://www.myserver.com/servlet/MyServletFrom inside FORM tag as scriptFrom inside FORM tag as script...

    From inside JHTML or JSP pageFrom inside JHTML or JSP pageUses Page CompilationCompiles the jsp file into a servlet on the fly, thenexecutes it

  • 8/8/2019 7735978-Servlets and the Java Web Server

    31/127

    Copyright 1997-8, Purple Technology Inc. 31

    Servlets and the Java Web Server

    11/04/08

    A Note on CLASSPATH and JWS

    JWS uses its own JREJWS uses its own JREThree ways to add classesThree ways to add classes

    Put the class files into the classes subdirectoryJar them, and put the jar files into the libsubdirectoryStart the server with the -classpath option

    httpd -classpath c:\projects\utils

  • 8/8/2019 7735978-Servlets and the Java Web Server

    32/127

    11/04/08 Copyright 1997-8, Purple Te 32

    Section III

    Writing ServletsWriting Servlets

  • 8/8/2019 7735978-Servlets and the Java Web Server

    33/127

    Copyright 1997-8, Purple Technology Inc. 33

    Servlets and the Java Web Server

    11/04/08

    The Servlet APIIndependent of Independent of

    web protocolserver brand or platformwhether it's local or remote

    Simple, small, easySimple, small, easyBase class provides core functionality; justBase class provides core functionality; just

    extend itextend it

    S l d h b S

  • 8/8/2019 7735978-Servlets and the Java Web Server

    34/127

    Copyright 1997-8, Purple Technology Inc. 34

    Servlets and the Java Web Server

    11/04/08

    CGI, or not, whichever Fairly generic interfaceFairly generic interfaceAccepts query, returns responseAccepts query, returns response

    Used for plugins, etc.Used for plugins, etc.

    S l d h J W b S

  • 8/8/2019 7735978-Servlets and the Java Web Server

    35/127

    Copyright 1997-8, Purple Technology Inc. 35

    Servlets and the Java Web Server

    11/04/08

    Servlet Architecture OverviewServlet InterfaceServlet Interface

    methods to manage servlet

    GenericServletGenericServletimplements Servlet interface

    HttpServletHttpServletextends GenericServlet

    exposes HTTP-specific functionality

    S l t d th J W b S

  • 8/8/2019 7735978-Servlets and the Java Web Server

    36/127

    Copyright 1997-8, Purple Technology Inc. 36

    Servlets and the Java Web Server

    11/04/08

    Servlet Architecture OverviewServletRequestServletRequest

    What the client says to the server Access to information like protocol, client IP#,

    parameters, and body

    ServletResponseServletResponseWhat the servlet says to the client

    HttpServletRequest, HttpServletResponseHttpServletRequest, HttpServletResponseHTTP-specific communication and informationState-tracking and session management

    S l t d th J W b S

  • 8/8/2019 7735978-Servlets and the Java Web Server

    37/127

    Copyright 1997-8, Purple Technology Inc. 37

    Servlets and the Java Web Server

    11/04/08

    Servlet Lifecycle OverviewServer loads and instantiates servletServer loads and instantiates servletServer calls init()Server calls init()

    LoopLoopServer receives request from clientServer calls service()service() calls doGet() or doPost()

    Server calls destroy()Server calls destroy()More detail to come later...More detail to come later...

    Ser lets and the Ja a Web Ser er

  • 8/8/2019 7735978-Servlets and the Java Web Server

    38/127

    Copyright 1997-8, Purple Technology Inc. 38

    Servlets and the Java Web Server

    11/04/08

    ServletRequestpassed to the service() methodpassed to the service() methodcontains lots of useful goodiescontains lots of useful goodies

    Client infoURL infoContent infoContent itself

    User-entered parameters

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    39/127

    Copyright 1997-8, Purple Technology Inc. 39

    Servlets and the Java Web Server

    11/04/08

    ServletRequest - Client InfogetRemoteAddr()getRemoteAddr()

    Returns the IP address of the agent that sent the requestgetRemoteHost()getRemoteHost()

    Returns the fully qualified host name of the agent thatsent the request

    getProtocol()getProtocol()Returns the protocol and version of the request as astring of the form /..

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    40/127

    Copyright 1997-8, Purple Technology Inc. 40

    Servlets and the Java Web Server

    11/04/08

    ServletRequest - URL InfogetScheme()getScheme()

    Returns the scheme of the URL used in this request, for example "http", "https", or "ftp".

    getServerName()getServerName()

    Returns the host name of the server that received therequest

    getServerPort()getServerPort()Returns the port number on which this request wasreceived

    getServletPath()getServletPath()Returns the URI path that got to this script, e.g./servlet/com.foo.MyServletUseful for putting in a tag

    See also getRequestURI() (in HttpServletRequest)

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    41/127

    Copyright 1997-8, Purple Technology Inc. 41

    Servlets and the Java Web Server

    11/04/08

    ServletRequest - Content InfogetContentLength()getContentLength()

    Returns the size of the request data

    getContentType()getContentType()Returns the MIME type of the request data

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    42/127

    Copyright 1997-8, Purple Technology Inc. 42

    Servlets and the Java Web Server

    11/04/08

    ServletRequest - ContentgetInputStream()getInputStream()

    Returns an input stream for reading binary data inthe request body.

    getReader()getReader()Returns a buffered reader for reading text in therequest body.

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    43/127

    Copyright 1997-8, Purple Technology Inc. 43

    Servlets and the Java Web Server

    11/04/08

    ServletRequest - ParametersString getParameter(String)String getParameter(String)

    Returns a string containing the lone value of the specified parameter,or null if the parameter does not exist.Was deprecated, but due to popular demand, it'll be undeprecated

    String[ ] getParameterValues(String)String[ ] getParameterValues(String)Returns the values of the specified parameter for the request as anarray of strings, or null if the named parameter does not exist.For parameters with multiple values, like lists

    Enumeration getParameterNames()Enumeration getParameterNames()Returns the parameter names for this request as an enumeration of strings, or an empty enumeration if there are no parameters or theinput stream is empty.

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    44/127

    Copyright 1997-8, Purple Technology Inc. 44

    Servlets and the Java Web Server

    11/04/08

    ServletResponseEmbodies the responseEmbodies the responseBasic use:Basic use:response.setContentType("text/html");PrintWriter out = response.getWriter();out.println(

    "Hello");

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    45/127

    Copyright 1997-8, Purple Technology Inc. 45

    Servlets and the Java Web Server

    11/04/08

    ServletResponse - OutputgetWriter()getWriter()

    for writing text data

    getOutputStream()getOutputStream()for writing binary dataor for writing multipart MIME

    you must call setContentType() beforeyou must call setContentType() before

    calling getWriter() or getOutputStream()calling getWriter() or getOutputStream() by default it's text/plain, which you don't want

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    46/127

    Copyright 1997-8, Purple Technology Inc. 46

    Servlets and the Java Web Server

    11/04/08

    The GenericServlet classimplements Servletimplements Servletalso implements Serializable, ServletConfigalso implements Serializable, ServletConfig

    implements all Servlet methodsimplements all Servlet methodsso you don't have to

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    47/127

    Copyright 1997-8, Purple Technology Inc. 47

    Servlets and the Java Web Server

    11/04/08

    The HelloWorld Servletimport javax.servlet.*;import java.io.*;public class HelloServlet extends GenericServlet{

    public void service(ServletRequest req,ServletResponse res)

    throws IOException, ServletException{

    res.setContentType("text/plain");ServletOutputStream out = res.getOutputStream();out.println("Hello, World!");

    }}

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    48/127

    Copyright 1997-8, Purple Technology Inc. 4811/04/08

    The HttpServlet classextends the GenericServlet base classextends the GenericServlet base classprovides a framework for handling theprovides a framework for handling theHTTP protocolHTTP protocolhas its own subclasses of ServletRequesthas its own subclasses of ServletRequestand ServletResponse that do HTTP thingsand ServletResponse that do HTTP things

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    49/127

    Copyright 1997-8, Purple Technology Inc. 4911/04/08

    HttpServlet methodsprovides helper methods for HTTP methodsprovides helper methods for HTTP methods

    doGet (GET and HEAD)doPost (POST)doPut, doDelete (rare)doTrace, doOptions (not overridden)

    the service() method dispatches requeststhe service() method dispatches requests

    to the do* methodsto the do* methods

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    50/127

    Copyright 1997-8, Purple Technology Inc. 5011/04/08

    HttpServlet: Receiving DatagetParameter / getParameterValues /getParameter / getParameterValues /getParameterNamesgetParameterNames

    process the data and return you the parametersgetQueryStringgetQueryString

    for GET methodreturns a single string in url-encoded format

    getReader / getInputStreamgetReader / getInputStreamfor POST, PUT, DELETEreturns a stream of characters / bytes

    mutually exclusivemutually exclusiveuse EITHER getParameter* OR one of the others (never

    both)

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    51/127

    Copyright 1997-8, Purple Technology Inc. 5111/04/08

    SimpleServlet (GET)public class SimpleServlet extends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponse res)

    throws ServletException, IOException {// set header field firstres.setContentType("text/html");// then get the writer and write the response dataPrintWriter out = res.getWriter();out.println(

    " SimpleServletOutput");

    out.println(" SimpleServlet Output ");out.println("

    This is output is from SimpleServlet.");out.println("");

    out.close();}public String getServletInfo() { return "A simple servlet"; }

    }

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    52/127

    Copyright 1997-8, Purple Technology Inc. 5211/04/08

    DateServlet public class DateServlet extends HttpServlet {

    public void service( HttpServletRequest req,

    HttpServletResponse res)throws ServletException, IOException

    {Date today = new Date();res.setContentType("text/plain");ServletOutputStream out = res.getOutputStream();out.println(today.toString());

    }public String getServletInfo() {

    return "Returns a string representation of the currenttime";

    }}

    From Java Web Server Tutorial by Sun Microsystems

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    53/127

    Copyright 1997-8, Purple Technology Inc.5311/04/08

    HelloHttpServletReads in a parameter Reads in a parameter

    Can use a form

    Can use right in a URL

    http://localhost:8080/servlet/HelloHttpServlet?name=Fred

    Outputs it as HTMLOutputs it as HTML

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    54/127

    Copyright 1997-8, Purple Technology Inc. 5411/04/08

    HelloHttpServletpublic class HelloHttpServlet extends HttpServletpublic class HelloHttpServlet extends HttpServlet{{

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

    ServletExceptionServletException{{

    String name = req.getParameter("name");String name = req.getParameter("name");if (name == null) name = "Joe";if (name == null) name = "Joe";

    res.setContentType("text/plain");res.setContentType("text/plain");ServletOutputStream out = res.getOutputStream();ServletOutputStream out = res.getOutputStream();out.println("Hello, " + name + "!");out.println("Hello, " + name + "!");

    }}}}

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    55/127

    Copyright 1997-8, Purple Technology Inc. 5511/04/08

    More Advanced ServletsSee Post ServletSee Post Servlet

    from Servlet Tutorial

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    56/127

    Copyright 1997-8, Purple Technology Inc. 5611/04/08

    HttpServletRequestCookie[ ] getCookies()Cookie[ ] getCookies()

    returns list of cookies sent by client

    String getMethod()String getMethod()GET, POST, etc.

    String getRequestURI()String getRequestURI()returns the URI or URL that was invoked

    useful for putting inside tag

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    57/127

    Copyright 1997-8, Purple Technology Inc. 5711/04/08

    HttpServletRequest (Cont.)CGI Variable MethodsCGI Variable Methods

    getServletPath(), getPathInfo(), getPathTranslated(),getQueryString(), getRemoteUser(), getAuthType()

    String getHeader(String name)String getHeader(String name)Session Management MethodsSession Management Methods

    HttpSession getSession(boolean create)

    More later...

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    58/127

    Copyright 1997-8, Purple Technology Inc. 5811/04/08

    HttpServletResponseContains HTTP status codes as constantsContains HTTP status codes as constants

    int HttpServletResponse.SC_NOT_FOUND = 404;

    Can send Error or Status codes to clientCan send Error or Status codes to clientDeals with CookiesDeals with CookiesDeals with HTTP HeadersDeals with HTTP HeadersCan send HTTP Redirect to clientCan send HTTP Redirect to client

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    59/127

    Copyright 1997-8, Purple Technology Inc. 5911/04/08

    Servlet Lifecycle: Init()public void init(ServerConfig cfg)public void init(ServerConfig cfg)called once, when servlet loadscalled once, when servlet loads

    don't worry about synchronization

    perform costly setup here, rather than onceperform costly setup here, rather than onceper requestper request

    open database connection(s)

    load in persistent dataspawn background threads

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    60/127

    Copyright 1997-8, Purple Technology Inc. 6011/04/08

    Init Detailsif you fail, throw an UnavailableExceptionif you fail, throw an UnavailableExceptionmust call super.init(cfg), which saves off must call super.init(cfg), which saves off cfgcfg

    if you like, you can save it yourself and overridegetServletConfig, but why bother?

    Can call getInitParameter(paramName) toCan call getInitParameter(paramName) to

    read from the server-side config fileread from the server-side config file

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    61/127

    Copyright 1997-8, Purple Technology Inc. 6111/04/08

    Servlet Lifecycle: Servicepublic void service(ServletRequest req,public void service(ServletRequest req,

    ServletResponse res)ServletResponse res)takes Request and Response objectstakes Request and Response objectscalled many times, once per requestcalled many times, once per request

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    62/127

    Copyright 1997-8, Purple Technology Inc. 6211/04/08

    service() and ConcurrencyMight be called simultaneously in severalMight be called simultaneously in severalthreadsthreads

    it is your responsibility to handle synchronizedaccess to shared resources

    It is possible to declare a servlet as single-It is possible to declare a servlet as single-threadedthreaded

    implement SingleThreadModel (empty interface) performance will suffer (if there are multiplesimultaneous requests)

    You can use class-static data to share data You can use class-static data to share dataacross successive or concurrent requestsacross successive or concurrent requests

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    63/127

    Copyright 1997-8, Purple Technology Inc. 6311/04/08

    Servlet Lifecycle: Destroypublic void destroy()public void destroy()

    takes no parametersyou must clean up

    close database connectionsstop threads

    Afterwards, servlet may be garbage collected

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    64/127

    Copyright 1997-8, Purple Technology Inc. 6411/04/08

    Servlet Lifecycle: Destroy DetailsThe server calls destroy after all service calls haveThe server calls destroy after all service calls havebeen completed, or after a certain number of been completed, or after a certain number of seconds have passed, whichever comes first.seconds have passed, whichever comes first.Warning: other threads might be running serviceWarning: other threads might be running service

    requests, so be sure to synchronize, and/or waitrequests, so be sure to synchronize, and/or waitfor them to quitfor them to quitSun's Servlet Tutorial has an example of how to do thiswith reference counting

    Destroy can not throw an exception, so if Destroy can not throw an exception, so if something bad happens, call log() with a helpfulsomething bad happens, call log() with a helpfulmessage (like the exception)message (like the exception)

    See closing a JDBC connection example in Tutorial

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    65/127

    Copyright 1997-8, Purple Technology Inc. 6511/04/08

    Init ParametersServletConfigServletConfig

    String getInitParameter()Enumeration getInitParameterNames()

    There are convenience methods of theThere are convenience methods of thesame name inside GenericServletsame name inside GenericServletInit Parameters are set by the server Init Parameters are set by the server

    administrator administrator Servlet Parameters are set by the web pageServlet Parameters are set by the web page

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    66/127

    Copyright 1997-8, Purple Technology Inc. 6611/04/08

    ServletContextcall GenericServlet.getServletContext()call GenericServlet.getServletContext()getServlets()getServlets()

    returns list of all installed Servlets

    getServlet(String name)getServlet(String name)returns the named Servlet

    log()log()see next slide

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    67/127

    Copyright 1997-8, Purple Technology Inc. 6711/04/08

    LoggingGenericServlet.log(String message)GenericServlet.log(String message)Writes the name of your servlet, plus the message,Writes the name of your servlet, plus the message,to the server log fileto the server log fileLocation of log file is server-specificLocation of log file is server-specific

    on JWS, you can check in the Admin Tool"If a servlet will have multiple instances (for example, if the"If a servlet will have multiple instances (for example, if thenetwork service runs the servlet for multiple virtual hosts),network service runs the servlet for multiple virtual hosts),the servlet writer should override this method. Thethe servlet writer should override this method. Thespecialized method should log an instance identifier, along specialized method should log an instance identifier, along

    with the requested message." - Javadoc for GenericServlet with the requested message." - Javadoc for GenericServlet But usually, there is only one instance of eachservlet, called reentrantly by the web server

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    68/127

    Copyright 1997-8, Purple Technology Inc. 6811/04/08

    Servlet.getServletInfo() You should override this method You should override this methodReturns a string containing author, version,Returns a string containing author, version,copyright, etc.copyright, etc.

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    69/127

    Copyright 1997-8, Purple Technology Inc. 6911/04/08

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    70/127

    Copyright 1997-8, Purple Technology Inc. 7011/04/08

    HTTP Servlet Efficiency

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    71/127

    Copyright 1997-8, Purple Technology Inc. 7111/04/08

    Efficiency: KeepAliveHTTP keepalive improves performanceHTTP keepalive improves performanceKeeps connection alive across multiple HTTPKeeps connection alive across multiple HTTPrequestsrequestsServlet must set content-lengthServlet must set content-length

    You can write to a ByteArray or StringBuffer, then You can write to a ByteArray or StringBuffer, thenget its length before writing itget its length before writing itres.setContentLength(sb.length());out.print(sb);

    KeepAlive should be enabled by default if all youKeepAlive should be enabled by default if all youdo is write short strings, then close the outputdo is write short strings, then close the outputstreamstream

    but maybe not

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    72/127

    Copyright 1997-8, Purple Technology Inc. 7211/04/08

    Efficiency: getLastModifiedlong HttpServlet.getLastModified(long HttpServlet.getLastModified(HttpServletRequest req )HttpServletRequest req )Returns the time the requested entity wasReturns the time the requested entity waslast modifiedlast modified

    difference in milliseconds between that time andmidnight, January 1, 1970negative = unknown (or dynamic)

    Improves performance on browser/proxyImproves performance on browser/proxycachingcaching

  • 8/8/2019 7735978-Servlets and the Java Web Server

    73/127

    11/04/08 Copyright 1997-8, Purple Te 73

    Section IV

    Saving StateSaving State

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    74/127

    Copyright 1997-8, Purple Technology Inc. 7411/04/08

    Saving State: WhyShopping CartShopping CartUser PreferencesUser PreferencesWizard interfacesWizard interfaces

    i.e., successive linked dialog boxes / form entry pages

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    75/127

    Copyright 1997-8, Purple Technology Inc. 7511/04/08

    Saving State: HowClient-side storageClient-side storage

    Hidden fieldsURL Rewriting

    CookiesServer-side storageServer-side storage

    Instance variables

    Database AccessJWS Session ManagementJWS Session Management

    Best possible solution (but still flawed)

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    76/127

    Copyright 1997-8, Purple Technology Inc. 7611/04/08

    Hidden FieldsSave data inside the servlet, keyed to aSave data inside the servlet, keyed to ahandlehandleStore a handle inside each successiveStore a handle inside each successiveFORMFORMUse that handle to retrieve data each queryUse that handle to retrieve data each queryOf course, you could always store all theOf course, you could always store all the

    data in hidden fields, insteaddata in hidden fields, instead

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    77/127

    Copyright 1997-8, Purple Technology Inc. 7711/04/08

    Hidden Fields: Exampleprivate Dictionary cache = new Hashtable();public void doGet(...) {

    String handle = getParameter(handle);

    UserData data;if (handle == null) {data = new UserData();handle = makeNewHandle(); // defined

    elsewherecache.put( handle, data );

    }else

    data = (UserData)cache.get(handle);

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    78/127

    Copyright 1997-8, Purple Technology Inc. 7811/04/08

    Hidden Fields: Exampleout.println();out.println(

    );

    out.println( ... rest of form ... );

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    79/127

    Copyright 1997-8, Purple Technology Inc. 7911/04/08

    Hidden Fields: ExampleSurvey.javaSurvey.java

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    80/127

    Copyright 1997-8, Purple Technology Inc. 8011/04/08

    Hidden Fields: Pros and ConsProsPros

    Well understoodYou have control

    Can use your own caching mechanism

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    81/127

    Copyright 1997-8, Purple Technology Inc. 8111/04/08

    Hidden Fields: Pros and ConsConsCons

    Need to use FORMshidden fields do not persist across normal links

    Sessions are not persistent across server restartsunless you write code to do it

    Sessions do not expireunless you write code to do it

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    82/127

    Copyright 1997-8, Purple Technology Inc. 8211/04/08

    URL RewritingChange HREF and ACTION URLs on the flyChange HREF and ACTION URLs on the flyChange /servlet/catalog intoChange /servlet/catalog into/servlet/catalog?user=1234/servlet/catalog?user=1234

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    83/127

    Copyright 1997-8, Purple Technology Inc. 8311/04/08

    URL RewritingPro:Pro:

    Dont need to use FORMs

    ConConLose user if he/she travels outside your web site

    Need to use Servlet for all accesses -- cant access araw HTML page

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    84/127

    Copyright 1997-8, Purple Technology Inc. 8411/04/08

    Using Instance Variables for State

    Session data stored in instance variablesSession data stored in instance variablesdirectly is bad - not valid for multiple usersindirectly is better - in a hashtable or vector, keyed

    off a unique handlePro: Quick, easyPro: Quick, easyCon: Not persistent, memory can fill upCon: Not persistent, memory can fill up

    easilyeasily

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    85/127

    Copyright 1997-8, Purple Technology Inc. 8511/04/08

    Database StateSession data stored in a databaseSession data stored in a database

    You should open a connection to the You should open a connection to thedatabase in your init() method, and close itdatabase in your init() method, and close itin your destroy() methodin your destroy() method

    You can still use the hidden field technique You can still use the hidden field techniqueWhen you get a handle, you pull in the user When you get a handle, you pull in the user

    data via a DB querydata via a DB query

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    86/127

    Copyright 1997-8, Purple Technology Inc. 8611/04/08

    Database State: Pros and ConsPro:Pro:

    persistenthigh capacity

    Con:Con:more complicatedhave to write more codestill doesnt automatically expire old sessions

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    87/127

    Copyright 1997-8, Purple Technology Inc. 8711/04/08

    C is for Cookie

    Cookie Monster is a trademark of Childrens Television Workshop

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    88/127

    Copyright 1997-8, Purple Technology Inc. 8811/04/08

    Whats A Cookie?Client-side storageClient-side storageServer can drop arbitrary data on browser Server can drop arbitrary data on browser Sent back to server on EVERY successiveSent back to server on EVERY successiverequestrequestAutomatically expiresAutomatically expiresCookies should be neither large nor Cookies should be neither large nor numerousnumerous

    Browsers should support twenty cookies per host, of at least four kilobytes each

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    89/127

    Copyright 1997-8, Purple Technology Inc. 8911/04/08

    Cookie Usessave session datasave session datasave handle to session datasave handle to session datastore user preferences for next sessionstore user preferences for next sessionstore user login informationstore user login information

    not very secure, but appropriate for someapplications

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    90/127

    Copyright 1997-8, Purple Technology Inc. 9011/04/08

    Cookies and ServletsServlets can easily use CookiesServlets can easily use CookiesHttpServletRequest.getCookies() methodHttpServletRequest.getCookies() methodHttpServletResponse.addCookie() methodHttpServletResponse.addCookie() methodCookie objectCookie object

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    91/127

    Copyright 1997-8, Purple Technology Inc. 9111/04/08

    javax.servlet.http.Cookieget/setName()get/setName()get/setValue()get/setValue()AttributesAttributes

    Comment, Domain, MaxAge, Path, Secure, Version

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    92/127

    Copyright 1997-8, Purple Technology Inc. 9211/04/08

    Cookie ExampleCookie Counter ServletCookie Counter Servlet

    Counter.java

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    93/127

    Copyright 1997-8, Purple Technology Inc. 9311/04/08

    Cookie Pros and ConsPro:Pro:

    No server-side storage requirementsSurvive server restarts

    Automatically expireCon:Con:

    Not supported by all browsersBandwidth limitations

    Not good for large amount of dataUser can disable them

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    94/127

    Copyright 1997-8, Purple Technology Inc. 9411/04/08

    Detecting Cookie AcceptanceCookieDetector.javaCookieDetector.javaDrops a cookie on the clientDrops a cookie on the clientSends a redirect back to CookieDetector,Sends a redirect back to CookieDetector,

    with a flag saying this is the test phasewith a flag saying this is the test phaseThe test phase detects whether The test phase detects whether

    The client accepted the cookieThe client rejected the cookie (or the browser doesnt support cookies)

    Sends another redirect to appropriate pageSends another redirect to appropriate pageYou can tell the user pretty please here

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    95/127

    Copyright 1997-8, Purple Technology Inc. 9511/04/08

    JWS Session ManagementFlexibleFlexibleLightweightLightweightGeneralGeneralAutomaticAutomaticUses cookies if it can, URL rewriting if itUses cookies if it can, URL rewriting if itcantcantBased on technology from ATGBased on technology from ATG

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    96/127

    Copyright 1997-8, Purple Technology Inc. 9611/04/08

    Session ObjectsServer-sideServer-sideOne per client (not one per servlet)One per client (not one per servlet)Preserved automaticallyPreserved automatically

    even in browsers that dont support cookiesExpire after 30 minutes (by default)Expire after 30 minutes (by default)Saved to disk if server dies; restored if Saved to disk if server dies; restored if server restartsserver restartsLoosely speaking, a session correspondsLoosely speaking, a session correspondsto a single sitting of a single anonymousto a single sitting of a single anonymoususer - JWS Tutorialuser - JWS Tutorial

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    97/127

    Copyright 1997-8, Purple Technology Inc. 9711/04/08

    Using SessionsHttpSession session = request.getSession

    (true);String info =

    (String)session.getValue(foo.info);// assume getNewInfo defined elsewhereString newinfo = getNewInfo();

    session.putValue(foo.info, newinfo);// then output page

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    98/127

    Copyright 1997-8, Purple Technology Inc. 9811/04/08

    URL RewritingPreserves sessions on non-cookie browsersPreserves sessions on non-cookie browsersChangesChanges

    intointo

    You must actively call You must actively call res.encodeUrl(/store/catalog)see next slide

    Does not work if user merely disables cookiesDoes not work if user merely disables cookiesHas to actually BE a non-cookie browser Lame

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    99/127

    Copyright 1997-8, Purple Technology Inc. 9911/04/08

    HttpServletResponse - EncodingHas methods to process URLs to splice in the session ID if Has methods to process URLs to splice in the session ID if appropriateappropriateNot the same as URLEncode / URLDecodeNot the same as URLEncode / URLDecode

    the server deals with that

    String encodeUrl(String url)String encodeUrl(String url)rewrites the given URL if necessaryif the browser supports cookies, returns URL unchangedAll URLs emitted by a session-using Servlet should be run throughthis method

    e.g.e.g.out.println("");

    also String encodeRedirectUrl(String url)also String encodeRedirectUrl(String url)

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    100/127

    Copyright 1997-8, Purple Technology Inc. 10011/04/08

    Session PersistenceSessions swap to diskSessions swap to disk

    When server shuts downWhen memory fills up

    Uses Java SerializationUses Java Serialization

    Only works for Serializable or Externalizableobjects

    Note: Session persistence is intended toNote: Session persistence is intended tobe used as a means for preservingbe used as a means for preservingSessions across server restarts. It is notSessions across server restarts. It is notmeant to be used as a general long-termmeant to be used as a general long-termsession persistence mechanism.session persistence mechanism.

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    101/127

    Copyright 1997-8, Purple Technology Inc. 10111/04/08

    ExampleVectorSessionServlet.javaVectorSessionServlet.java

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    102/127

    Copyright 1997-8, Purple Technology Inc. 10211/04/08

    BugsCant use custom classes inside sessionCant use custom classes inside sessiondatadataDoesnt really detect whether clientDoesnt really detect whether clientsupports cookiessupports cookies

    Instead, detects whether browser can potentiallysupport cookiesLame - they should use my CookieDetector technique

  • 8/8/2019 7735978-Servlets and the Java Web Server

    103/127

    11/04/08 Copyright 1997-8, Purple Te 103

    Section V

    Java Web Server FeaturesJava Web Server Features

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    104/127

    Copyright 1997-8, Purple Technology Inc. 10411/04/08

    Administration ToolsPlay with Admin ToolPlay with Admin Tool

    http://localhost:9090/

    Click on a service, click Manage buttonClick on a service, click Manage buttonTo shut down server, click Shut DownTo shut down server, click Shut Down

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    105/127

    Copyright 1997-8, Purple Technology Inc. 10511/04/08

    Manage ServletsAddAddPropertiesProperties

    Load on Startup

    UnloadUnload

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    106/127

    Copyright 1997-8, Purple Technology Inc. 10611/04/08

    Servlet AliasesSpecify a partial URLSpecify a partial URLMap it to a particular servletMap it to a particular servlete.g.e.g.

    you want http://foo.com/lunch to execute/servlets/meal?type=lunchset alias = /lunch

    set servlet invoked = meal?type=lunch

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    107/127

    Copyright 1997-8, Purple Technology Inc. 10711/04/08

    Servlet Chains (Filters)specify a comma-separated list of servletsspecify a comma-separated list of servletsthe first servlet gets the user inputthe first servlet gets the user inputeach servlet in turn will get the previouseach servlet in turn will get the previousoutputoutputthe final servlet will return to the user the final servlet will return to the user all servlets in chain must use same ACLall servlets in chain must use same ACL

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    108/127

    Copyright 1997-8, Purple Technology Inc. 10811/04/08

    HTML TemplatesDefine standard look for all (or some) pagesDefine standard look for all (or some) pagesTemplate ServletTemplate ServletA tag inside template page inserts sectionA tag inside template page inserts sectionfrom original pagefrom original page

    Specify which files are templated viaSpecify which files are templated viaServlet Aliases in Admin ToolServlet Aliases in Admin Tool

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    109/127

    Copyright 1997-8, Purple Technology Inc. 10911/04/08

    Page Compilation (JSP)Embed Java code in static HTML pagesEmbed Java code in static HTML pagesthen compile those pages into individualthen compile those pages into individualJava servlets to create a dynamic web siteJava servlets to create a dynamic web site

    Based on JHTML technology from ArtBased on JHTML technology from ArtTechnology Group (http://www.atg.com/)Technology Group (http://www.atg.com/)

    Product: Dynamo, a Java Web Application Server

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    110/127

    Copyright 1997-8, Purple Technology Inc. 11011/04/08

    Session TrackingSee aboveSee above

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    111/127

    Copyright 1997-8, Purple Technology Inc. 11111/04/08

    Servlet BeansUsing Servlets That are BeansUsing Servlets That are Beans

    Changes to config file are instantly updatedServlet itself is persistent across server restarts

    instance variables, like counters or caches, are preserved

    Calling JavaBeans from ServletsCalling JavaBeans from ServletsInvisible BeansInstalled inside lib subdirectory

    Calling JavaBeans in JHTML/JSP FilesCalling JavaBeans in JHTML/JSP Files

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    112/127

    Copyright 1997-8, Purple Technology Inc. 11211/04/08

    FAQAnswers in the Exercises bookAnswers in the Exercises book

    How do I develop using the servlet classes withoutinstalling JDK1.2?Is it the servlets directory or the servlet directoryWhy doesnt my servlet work inside a tag?How do I support both GET and POST protocolfrom the same Servlet?How do I fully shut down the server?My browser says the server returned an invalid or unrecognized response what gives?

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    113/127

    Copyright 1997-8, Purple Technology Inc. 11311/04/08

    ReferencesJava Server 1.1Java Server 1.1

    http://java.sun.com/javastore/jserv/buy_try.htmlhttp://java.sun.com/products/java-server/index.html

    be sure to download the JWS documentationThe home for servlets and the Java Web Server.The home for servlets and the Java Web Server.

    http://jserv.javasoft.comThe Java Web Server 1.1 is available for trial or purchase.The Java Web Server 1.1 is available for trial or purchase.

    http://java.sun.com/javastore/jserv/buy_try.htmlThe Java Web Server 1.1.1 upgrade pack is available for free.The Java Web Server 1.1.1 upgrade pack is available for free.

    http://java.sun.com/products/java-server/webserver/jws111.html

    The Java Server Pages preview pack is available for free.The Java Server Pages preview pack is available for free.http://developer.javasoft.com/developer/earlyAccess/jws- preview.html

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    114/127

    Copyright 1997-8, Purple Technology Inc. 11411/04/08

    ReferencesRFC2045 - MIMERFC2045 - MIME

    http://info.internet.isi.edu/in-notes/rfc/files/rfc2045.txt

    RFC 2109 - CookiesRFC 2109 - Cookies

    http://info.internet.isi.edu/in-notes/rfc/files/rfc2109.txtLive SoftwareLive Software

    http://www.livesoftware.com/JRun, many commercial servlets

    ATG - Dynamo Web Application Server ATG - Dynamo Web Application Server http://www.atg.com/

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    115/127

    Copyright 1997-8, Purple Technology Inc. 11511/04/08

    ReferencesAdvanced Web TechnologiesAdvanced Web Technologies

    http://www.javatrain.com/

    Purple TechnologyPurple Technologyhttp://www.purpletech.com/

    GamelanGamelanhttp://java.developer.com/

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    116/127

    Copyright 1997-8, Purple Technology Inc. 11611/04/08

    Appendix: CGI Tutorial

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    117/127

    Copyright 1997-8, Purple Technology Inc. 11711/04/08

    What Is CGI?Common Gateway InterfaceCommon Gateway InterfaceAllows web pages to send parameters toAllows web pages to send parameters toweb server web server

    Use HTML forms on client sideUse HTML forms on client sideCan also use Java it's just a protocol!

    Use scripts on server sideUse scripts on server side

    Can use Servlets!

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    118/127

    Copyright 1997-8, Purple Technology Inc. 11811/04/08

    Example CGI HTMLName:
    Message:

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    119/127

    Copyright 1997-8, Purple Technology Inc. 11911/04/08

    CGI FlowBrowser downloads HTML page containingBrowser downloads HTML page containingFORM tagFORM tagBrowser lays out input widgetsBrowser lays out input widgets

    User fills out form and clicks "Submit"User fills out form and clicks "Submit"Browser takes parameters and sends themBrowser takes parameters and sends themin CGI formatin CGI format

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    120/127

    Copyright 1997-8, Purple Technology Inc. 12011/04/08

    CGI Flow (Cont.)Server receives parameters and sendsServer receives parameters and sendsthem to CGI scriptthem to CGI scriptCGI script returns MIME documentCGI script returns MIME document

    usually it's "text/html"can be any MIME type

    Browser receives response document andBrowser receives response document and

    displays itdisplays itIf response contains FORM tag, whole thingIf response contains FORM tag, whole thingcan happen againcan happen again

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    121/127

    Copyright 1997-8, Purple Technology Inc. 12111/04/08

    The FORM tagOpens a formOpens a formACTIONACTION

    the URL of the script to execute

    METHODMETHODGET or POSTUsually use POST

    closed with closed with

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    122/127

    Copyright 1997-8, Purple Technology Inc. 12211/04/08

    INPUT TYPE=textSpecifies a text fieldSpecifies a text fieldNAMENAME

    names parameter to be passed to script

    VALUE (optional)VALUE (optional)initial value for text

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    123/127

    Copyright 1997-8, Purple Technology Inc. 12311/04/08

    INPUT TYPE=textareaSpecifies a multi-line text areaSpecifies a multi-line text areaNAMENAME

    names parameter to be passed to script

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    124/127

    Copyright 1997-8, Purple Technology Inc. 12411/04/08

    INPUT TYPE=checkboxSpecifies a check box (duh)Specifies a check box (duh)NAMENAME

    names parameter to be passed to script

    ISCHECKED=trueISCHECKED=truedefault value on

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    125/127

    Copyright 1997-8, Purple Technology Inc. 12511/04/08

    INPUT TYPE=radioSpecifies a radio button (or groupedSpecifies a radio button (or groupedcheckbox)checkbox)NAMENAME

    names group of buttonsVALUEVALUE

    specifies the value for the groupe.g.e.g.

    MaleFemale

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    126/127

    Copyright 1997-8, Purple Technology Inc. 12611/04/08

    INPUT TYPE=submitA push button that submits the formA push button that submits the formNAMENAME

    specifies name of variable

    VALUEVALUEspecifies name of buttonyes, "value" specifies the name

    hey, I didn't write the spec

    Servlets and the Java Web Server

  • 8/8/2019 7735978-Servlets and the Java Web Server

    127/127

    INPUT TYPE=resetA push button that clears the formA push button that clears the formDoes not submit itDoes not submit it