Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Web Application                       Architecture                 (based J2EE 1.4 Tutorial)                              ...
Disclaimer & Acknowledgments?   Even though Sang Shin is a full-time employee of    Sun Microsystems, the contents here ar...
Agenda               ?   Web application, components and Web container               ?   Technologies used in Web applicat...
Web Application &               Web Components &                 Web Container                                   4So lets ...
Web Components & Container                    Applet Container                                 Web Container              ...
Web Components & Container               ?   Web components are in the form of either                   Servlet or JSP (al...
Web Application & Components                ?   Web Application is a deployable package                    –   Web compone...
Technologies Used    In Web Application                         8.                             8
Web Request Handling                                                                         9In the Java 2 platform, web ...
Java Web Application Technologies                                                                         10Servlets are J...
Web Application                    Development and                    Deployment Steps               (using hello2 example...
Web Application Development                 and Deployment Steps                 1.Write (and compile) the Web component c...
1. Write and compile the Web                component code                ?   Create development tree structure           ...
Development Tree Structure                 ?   Keep Web application source separate from                     compiled file...
Example: hello2 Tree Structure                (before “ant build” command)                ?   Hello2                     –...
2. Create any static resources                 ?   HTML pages                     –   Custom pages                     –  ...
3. Create deployment                descriptor (web.xml)                ?   Deployment descriptor contains                ...
4. Build the Web application                 ?   Either *.WAR file or unpacked form of                     *.WAR file     ...
Example: hello2 Tree Structure                (after “asant build” command)                ?   Hello1                     ...
5. Deploy Web application               ?   Deploy the application over deployment                   platform such as Sun ...
6. Perform Client Access to                Web Application                ?   From a browser, go to URL of the Web        ...
http://localhost:8080/hello1/greeting                                                                       22So for the h...
Running Web Application                                                                       23This is response html page...
Web Application                  Archive (*.WAR)                                     24OK, now lets talk about WAR file.  ...
Web Application                ?   Web application can be deployed in two                    different forms              ...
What is *.WAR file?                ?   Ready to deployable package over web                    container                ? ...
Document Root & Context                 ?   Document Root of the Web application                     –   Top-level directo...
Directory Structure of       *.WAR file                                                                           28This p...
Directory Structure of    *.WAR file                             29.                                  29
How to Create *.WAR file?               ?   3 different ways                   –   Use IDE (NetBeans)                   – ...
Example: Creating hello2.war via“asant create-war” commandC:j2eetutorial14exampleswebhello2>asant create-warBuildfile: bui...
Example: Creating hello2.war via               jar command               C:j2eetutorial14exampleswebhello2build>jar cvf he...
WEB-INF Directory                 ?   Subdirectory of Document root                 ?   Contains                     –   w...
HTTP request URL & Web                component URL (alias) & Context                ?   Request URL: User specified acces...
Configuring              Web Application via                   web.xml                                                    ...
Configuring Web Application                 ?   Configuration information is specified in                     web.xml (Web...
Web Applications Deployment                Descriptor (web.xml)                 ?   Prolog                 ?   Alias Paths...
Web Applications Deployment                 Descriptor (web.xml)                 ?   Case sensitive                 ?   Or...
Prolog (of web.xml)                 ?   Every XML document needs a prolog                 <?xml version="1.0" encoding="IS...
Alias Paths (of web.xml)                 ?   When a request is received by Servlet container,                     it must ...
Alias Paths (of web.xml)                 <servlet>                       <servlet-name>greeting</servlet-name>            ...
Context and Initialization               Parameters (of web.xml)              ?   Represents application context          ...
Event Listeners (of web.xml)                  ?   Receives servlet life-cycle events                      <listener>      ...
Filter Mappings (of web.xml)                ?   Specify which filters are applied to a                    request, and in ...
Error Mappings (of web.xml)                 ?   Maps status code retURLed in an HTTP                     response to a Jav...
References (of web.xml)                 ?   Need when web components make                     references to environment en...
Example web.xml of hello2                <?xml version="1.0" encoding="UTF-8"?>                <web-app xmlns="http://java...
Passion!           48                48
Upcoming SlideShare
Loading in …5
×

Web Application Architecture

807 views

Published on

This presentation is not created by me. I got this from internet some year back. I could not find the link from where I downloaded it. So I thought I can make it available for all to use. If someone finds the link please send me. I will remove this presentation from here.

Published in: Technology
  • Be the first to comment

Web Application Architecture

  1. 1. Web Application Architecture (based J2EE 1.4 Tutorial) 1In this session, I am going to talk about what a typical Web applicationlooks like. I will also show you how to build a Web application by goingthrough step by step guideline. Most of the contents in this presentation ismade from “Chapter 4: Web Application” tutorial section of Java WSDP. 1
  2. 2. Disclaimer & Acknowledgments? Even though Sang Shin is a full-time employee of Sun Microsystems, the contents here are created as his own personal endeavor and thus does not reflect any official stance of Sun Microsystems.? Sun Microsystems is not responsible for any inaccuracies in the contents.? Acknowledgments – The slides of this presentation are made from “Web Application” section of J2EE 1.4 tutorial written by Sun Microsystems 2 2
  3. 3. Agenda ? Web application, components and Web container ? Technologies used in Web application ? Web application development and deployment steps ? Web Application Archive (*.WAR file) – *.WAR directory structure – WEB-INF subdirectory ? Configuring Web application – Web application deployment descriptor (web.xml file) 3So this is the list of topics we are going to talk about in this session.First, we will define a few terms: “web application”, “web components” and “webcontainer”. Next, we will talk about the steps you will follow to develop anddeploy a web application. Then we will talk about “Web Application Archive”,which is called WAR file in short. We will look into the directory structure of aWAR file especially a meta sub-directory called WEB-INF.A Web application has a accompanying configuration file called web.xml. Thisfile is referred to as the deployment descriptor of the web application and containsall the configuration information of the application that web container needs toknow in order to deploy and run the application properly. Understanding theweb.xml file is important since you are going to have to construct web.xml file aspart of development of your web application.Then we will go through some life-cycle operations that you can perform overyour web applications, for example, installing and deploying, listing all webapplications that are currently running on the target web container and updating,removing, undeploying them. 3
  4. 4. Web Application & Web Components & Web Container 4So lets understand a few terms. 4
  5. 5. Web Components & Container Applet Container Web Container EJB Container Applet HTTP/ JSP Servlet RMI EJB HTTPS J2SE RMI/IIOP RMI/IIOP JavaMail JavaMail JDBC JDBC JMS JTA JNDI JNDI JMS JTA App Client JAF Container JAF App HTTP/ J2SE Client HTTPS RMI RMI/IIOP JDBC JNDI JMS J2SE J2SE Database 5I talked about the container and component model of J2EE architecture during theJ2EE overview session. Under component and container architecture of J2EE, thebusiness logic (typically as EJBs), contents or presentations (typically as web-tiercomponents such as Servlet and JSP components) are captured in the form ofcomponents and those components are then run within corresponding host executionenvironment called containers. (I am using the term “components” a bit loosely herefor Servlet and JSP since they are not really components in a strict sense.)In the web-tier container, the components are constructed in the form of webcomponents and web components can be either in the form of servlet or JSP pageswhile in the EJB-tier container, the components are constructed in the form of EJBbeans. 5
  6. 6. Web Components & Container ? Web components are in the form of either Servlet or JSP (along with JavaBeans and custom tags) ? Web components run in a Web container – Tomcat and Resin are popular web containers – All J2EE compliant app servers (Sun Java System App Server) provide web containers ? Web container provides system services to Web components – Request dispatching, security, and life cycle management 6So just to repeat what I just said, web components are in the form of either servlet orJSP pages. And web components run in a web container. And there are a few popularweb containers out there, for example, Tomcat and Resin are two most popular webcontainers.I said that containers provide host execution environment for the components providingsome system services. For web components, the web container provides several systemservices, for example, receiving service requests from clients and then dispatching themto appropriate web components, and life cycle management of your components. Forexample, the web container can figure out when it is the time to create an instance ofservlet class to handle the incoming service request and when to remove the instance. 6
  7. 7. Web Application & Components ? Web Application is a deployable package – Web components (Servlets and JSPs) – Static resource files such as images – Helper classes – Libraries – Deployment descriptor (web.xml file) ? Web Application can be represented as – A hierarchy of directories and files (unpacked form) or – *.WAR file reflecting the same hierarchy (packed form) 7OK. We have talked a bit on what a web component is, and how web components runin a web container. Now lets talk about a web application. A web application isbasically a collection of everything that constitutes a deployable package. Thedeployable package contains multiple web components, that is, multiple servlets andJSP pages, and static resource files such as images that are part of displayable HTMLpages, helper classes that are used by the web components, and library classes andfinally deployment descriptor (web.xml file).A Web application is defined as a hierarchy of directories and files in a standard layoutas specified in Servlet specification. Such a hierarchy can be accessed in its unpackedform, where each directory and file exists in the file system separately, or in a packedform known as a Web Application Archive, or WAR file. The former format is moreuseful during development, while the latter is used when you distribute your applicationto the target platform. 7
  8. 8. Technologies Used In Web Application 8. 8
  9. 9. Web Request Handling 9In the Java 2 platform, web components provide the dynamic extension capabilities fora web server. Web components are either Java servlets, JSP pages, or web serviceendpoints. The interaction between a web client and a web application is illustrated inthe figure of the slide.The client sends an HTTP request to the web server. A web server that implements JavaServlet and JavaServer Pages technology converts the request into anHTTPServletRequest object. This object is delivered to a web component, which caninteract with JavaBeans components or a database to generate dynamic content. Theweb component can then generate an HTTPServletResponse or it can pass the request toanother web component. Eventually a web component generates aHTTPServletResponse object. The web server converts this object to an HTTP responseand returns it to the client. 9
  10. 10. Java Web Application Technologies 10Servlets are Java programming language classes that dynamically process requests andconstruct responses. JSP pages are text-based documents that execute as servlets butallow a more natural approach to creating static content. Although servlets and JSPpages can be used interchangeably, each has its own strengths. Servlets are best suitedfor service-oriented applications (web service endpoints are implemented as servlets)and the control functions of a presentation-oriented application, such as dispatchingrequests and handling nontextual data. JSP pages are more appropriate for generatingtext-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless MarkupLanguage (WML), and XML.Since the introduction of Java Servlet and JSP technology, additional Java technologiesand frameworks for building interactive web applications have been developed. Thesetechnologies and their relationships are illustrated in the figure. 10
  11. 11. Web Application Development and Deployment Steps (using hello2 example under J2EE 1.4 tutorial) 11Now lets go over the steps needed for the development and deployment ofa web application. 11
  12. 12. Web Application Development and Deployment Steps 1.Write (and compile) the Web component code (Servlet or JSP) and helper classes referenced by the web component code 2.Create any static resources (for example, images or HTML pages) 3.Create deployment descriptor (web.xml) 4.Build the Web application (*.war file or deployment-ready directory) 5.Deploy the web application into a Web container ? Web clients are now ready to access them via URL 12So this is the list of steps you will follow in order to develop and deploy a webapplication. First, you will write and compile the web component code. Webcomponent code is either servlet Java code or JSP pages and helper classes that are usedby the web components. You also need to create any static resources such as images orHTML pages. Next, you will create deployment descriptor, that is, the web.xml file.Then you will build web application. As was mentioned, a web application can beeither in the form of *.war file (packed form) or laid-out form of *.war file (unpackedform) as was discussed in previous slide. A *.war file will be a compressed file with thesame layout as the build directory.Then you will deploy the web application to the web container. We will discuss thedifference between “installation” and “deployment” later on. (There is a fine distinctionbetween the two.)Once a web application is deployed, then client can access the web components throughthe HTML browser. So lets go over each of these steps one by one. 12
  13. 13. 1. Write and compile the Web component code ? Create development tree structure ? Write either servlet code or JSP pages along with related helper code ? Create build.xml for Ant-based build (and other application development life-cycle management) process ? IDE (i.e. NetBeans) handles all these chores 13So the first step is to write and compile web component code. Now just like any otherapplication development, you might want to create development directory structure thatfits your need. As we will see in the following slide, people have recommendeddirectory structure they found suitable for web application development. (This is only arecommendation, of course.)Once you create an appropriate development directory structure, you can then writeservlet or JSP along with related helper classes and other pieces. Now another thingpeople find quite useful is to use ANT build tool for the development and deploymenttasks of web applications. As we will see later on, ANT is basically platformindependent make utility. And the file that contains the build instructions that ANTuses is called build.xml file. 13
  14. 14. Development Tree Structure ? Keep Web application source separate from compiled files – facilitate iterative development ? Root directory (example from hello2 sample code from J2EE 1.4 tutorial) – build.xml: Ant build file – src: Java source of servlets and JavaBeans components – web: JSP pages and HTML pages, images 14In order to facilitate iterative development/deployment and also in order to keep sourcecode separate from compiled files, the source code for the tutorial examples is stored inthe following structure under each application directory, for example, for hello1 webapplication:? build.xml - Ant build file? context.xml - Optional application configuration file? src - Java source of servlets and JavaBeans components? web - JSP pages and HTML pages, imagesThe Ant build files (build.xml) distributed with the examples contain*targets for creating an unpacked WAR structure in the build subdirectory of the hello1application*targets for copying and compiling files from the src directory to the build directory*targets for invoking the web containers manager commands to install, reload,remove, deploy, and undeploy applications. 14
  15. 15. Example: hello2 Tree Structure (before “ant build” command) ? Hello2 – src/servlets ? GreetingServlet.java ? ResponseServlet.java – web ? WEB-INF – web.xml ? duke.waving.gif – build.xml 15So this is an example directory structure of hello1 web application you find in the JavaWSDP. There are two servlet Java source files. And there is a web directory called webwhich contains WEB-INF directory and other static resource files.You will code each web component in the src directory. 15
  16. 16. 2. Create any static resources ? HTML pages – Custom pages – Login pages – Error pages ? Image files that are used by HTML pages or JSP pages – Example: duke.waving.gif 16The next step is to create any static resources that will be used by the web components.And they include some static HTML pages or image files that are used by the HTMLpages or JSP pages. And an example of image is duke that you see quite often invarious Java-related web pages.Static resources such as image file are stored in the applications web directory. 16
  17. 17. 3. Create deployment descriptor (web.xml) ? Deployment descriptor contains deployment time runtime instructions to the Web container – URL that the client uses to access the web component ? Every web application has to have it 17The next step is to create deployment descriptor, web.xml file. By the way, the name ofthis file has to be web.xml file. Now web.xml file contains deployment time andruntime instructions to the web container. For example, you can specify the URN thatclients of your web applications will use to access your web components. (We will talkabout this URN later on in detail.) Every web application has to have a web.xml file.The web.xml file is coded and stored in the applications webWEB-INF directory. 17
  18. 18. 4. Build the Web application ? Either *.WAR file or unpacked form of *.WAR file ? Build process is made of – create build directory (if it is not present) and its subdirectories – compile Java code into build/WEB-INF/classes directory ? Java classes reside under ./WEB-INF/classes directory – copy web.xml file into build/WEB-INF directory – copy image files into build directory 18Once you have all the pieces, you can create a web application. As mentioned before, aweb application is basically a deployable package that contains everything that isneeded for the deployment.As mentioned before, a web application is either in the form or *.war file (packed) orlaid out form of the war file (unpacked). Typically a build process for the webapplication involves creating “build” directory which functions as the root directory forthe compile time generated pieces such as java classes and pieces that are needed tocreate *.war file such as web.xml file.For example, the compiled Java classes will end up residing in “build/WEB-INF/classes” directory and web.xml will be copied into “build/WEB-INF” directory andthe image files will be copied into the “build” directory itself. Basically the “build”directory is the reflection of directory structure that a particular web container expects(in unpacked form). 18
  19. 19. Example: hello2 Tree Structure (after “asant build” command) ? Hello1 – src – web – build.xml – build ? WEB-INF – classes ? GreetingServlet.class ? ResponseServlet.class – web.xml ? duke.waving.gif 19So this is an example of hello1 web application. Once the build process is completedvia “ant build” command, “build” directory gets created if it is not present before, andGreetingServlet.class and ResponseServlet.class class files are put into “classes”subdirectory of WEB-INF directory and web.xml file is copied from “web” directory to“build/WEB-INF” directory and image file is copied from “web” directory into “build”directory. Now the build directory is now ready to be taken either as a source directoryfor creating *.war file (packed form) or can be copied over to web container (unpackedform) for deployment. 19
  20. 20. 5. Deploy Web application ? Deploy the application over deployment platform such as Sun Java System App Server or Tomcat ? 3 ways to deploy to Sun Java System App server – asadmin deploy --port 4848 --host localhost – passwordfile "c:j2eetutorial14examplescommonadmin- password.txt" --user admin hello2.war (asant deploy-war) – App server admin console – NetBeans 20Once you built a ready-to-deployable web application, you can now deploy theapplication over the web container. 20
  21. 21. 6. Perform Client Access to Web Application ? From a browser, go to URL of the Web application 21Once your web application has been deployed, then a client (typically a browser) can tryto access the web resources by specifying the appropriate URN address. 21
  22. 22. http://localhost:8080/hello1/greeting 22So for the hello1 example web application, a client will specifyhttp://localhost:8080/hello1/greeting to access the hello1 web resource. 22
  23. 23. Running Web Application 23This is response html page that gets displayed as a result of the web resourcehandling of the first HTTP request that comes from the client. 23
  24. 24. Web Application Archive (*.WAR) 24OK, now lets talk about WAR file. 24
  25. 25. Web Application ? Web application can be deployed in two different forms – a *.war file or – an unpacked directory laid out in the same format as a *.war file (build directory) ? Use *.war file when you have to deploy on a remote machine – asant deploy-war command 25As was mentioned a couple of times already, a web application can be installed ordeployed in two different forms, either as a *.war file (packed form) or unpackeddirectory that reflects the same directory structure of the *.war file.Now when you “install”, you can use either form while when you do “deploy” you canuse only *.war file. And I will explain why this is the case later on. 25
  26. 26. What is *.WAR file? ? Ready to deployable package over web container ? Similar to *.jar file ? Contains things to be deployed – Web components (servlets or JSPs) – Server-side utility classes – Static Web presentation content (HTML, image, etc) – Client-side classes (applets and utility classes) ? Reflects contents in build directory 26So what is war file? It is a ready-to-deployable package over web container. It is like*.jar file and obviously contains things that need to be deployed over the container suchas web service components (servlets, JSP pages), server side helper or utility classes,static resources, and sometimes applet classes that would be needed by the client.As was mentioned before, it reflects the contents of the “build” directory we talkedabout. 26
  27. 27. Document Root & Context ? Document Root of the Web application – Top-level directory of WAR – Contains JSP pages, client-side classes and archives, and static Web resources are stored – Also contains WEB-INF directory ? A context is a name that gets mapped to the document root of a Web application – /hello1 is context for hello1 example – Distinguishes a Web application in a single Web container – Has to be specified as part of client URL 27Now lets talk about *.war files directory structure a bit. The top level directory of thewar file is called “document root” of the web application. And the “document root”directory contains JSP pages, client side classes and archive file such as applet code andstatic web resources.The document root also contains WEB-INF directory.Now one terminology you have heard many times (but maybe were not sure what itexactly is) is what is called “web application context” or “context” in short. Basicallythe context is the name of the document root of your web application. For example,/hello1 is the context name of hello1 example. Context is a way to distinguish variousweb applications in a single web container.The context has to be specified as part of “request path” that is specified by the client.(We will talk about “request path” later on in this presentation.) 27
  28. 28. Directory Structure of *.WAR file 28This picture shows the directory structure of *.war file. Please note that the“WebApplicationName” directory reflects the Document root, thus the context. 28
  29. 29. Directory Structure of *.WAR file 29. 29
  30. 30. How to Create *.WAR file? ? 3 different ways – Use IDE (NetBeans) – Use ant tool after putting proper build instruction in build.xml file ? “asant create-war” (under J2EE 1.4 tutorial) – Use “jar cvf <filename>.war .” command under build directory 30So how do you create a *.war file? There are 3 different ways to create *.war file. Ifyou are using an IDE, creating and deploying *.war file gets handled via one or twoclicks. For J2EE 1.4 tutorial sample applications, you can use “asant create-war” commandwith proper build scripts. Or you can use “jar” command to create the war file. Jarcommand in this case is like zip utility. 30
  31. 31. Example: Creating hello2.war via“asant create-war” commandC:j2eetutorial14exampleswebhello2>asant create-warBuildfile: build.xml...create-war: [echo] Creating the WAR.... [delete] Deleting: C:j2eetutorial14exampleswebhello2assemblewarhello2.war [delete] Deleting directory C:j2eetutorial14exampleswebhello2assemblewarWEB-INF [copy] Copying 1 file to C:j2eetutorial14exampleswebhello2assemblewarWEB-INF [copy] Copying 2 files to C:j2eetutorial14exampleswebhello2assemblewarWEB-INFclasses [war] Building war: C:j2eetutorial14exampleswebhello2assemblewarhello2.war [copy] Copying 1 file to C:j2eetutorial14exampleswebhello2 31 31
  32. 32. Example: Creating hello2.war via jar command C:j2eetutorial14exampleswebhello2build>jar cvf hello2.war . added manifest adding: duke.waving.gif(in = 1305) (out= 1295)(deflated 0%) adding: servlets/(in = 0) (out= 0)(stored 0%) adding: servlets/GreetingServlet.class(in = 1680) (out= 887)(deflated 47%) adding: servlets/ResponseServlet.class(in = 1090) (out= 572)(deflated 47%) C:j2eetutorial14exampleswebhello2build>jar xvf hello2.war created: META-INF/ extracted: META-INF/MANIFEST.MF extracted: duke.waving.gif created: servlets/ extracted: servlets/GreetingServlet.class extracted: servlets/ResponseServlet.class 32So in this example, I am creating hello2.war file using “jar” command. Basically you“cd” to “build” directory and then use “jar” command to pick up all the piecesunderneath it into the “hello2.war” file. Please dont forget the dot(.) at the end in thisexample.In the lower part of the slide, I use “jar tvf” command just to show the contents of thenewly created *.war file. 32
  33. 33. WEB-INF Directory ? Subdirectory of Document root ? Contains – web.xml : Web application deployment descriptor – JSP tag library descriptor files – Classes : A directory that contains server-side classes: servlets, utility classes, and JavaBeans components – lib : A directory that contains JAR archives of libraries (tag libraries and any utility libraries called by server-side classes) 33Now what is this WEB-INF directory? WEB-INF directory contains web.xml file, JSPtag library descriptor files (we have not learned this yet so dont worry about it if youdont understand), and “classes” directory that contains servlet classes and “lib”directory that contains various jar files that could contain Java classes that are used bythe web components and their helper classes. 33
  34. 34. HTTP request URL & Web component URL (alias) & Context ? Request URL: User specified access point of a web resource – http://[host]:[port]/[request path]?[query string] – [request path] is made of context and web components URL – http://localhost:8080/hello1/greeting?username=Monica ? Context: Name of the root document of a web application – Identifies a particular application on that server – /hello1 is context 34Now I would like to talk about how a client can access the web service and explainsome related terms.First “request URL” is user specified access point of a web resource. This is somethingthat is being passed to the web components as part of HTTP request. The typicalrequest URL is made of http://[host]:[port]/[request path]?[query string]The [request path] is made of “context” of the web application and the “URN of the webcomponent”. For example, in the case hello1 example, “/hello1” is context and“/greeting” is the URN of the web component. So the [request path] will look like“/hello1/greeting”. Now as mentioned before, context is the name of the root documentof the web application. And as a web application developer/deployer, you can chooseany name as context name for your application. The context name is specified in theweb.xml deployment descriptor. 34
  35. 35. Configuring Web Application via web.xml 35Now lets talk about how to configure your web application using web.xmldeployment descriptor. 35
  36. 36. Configuring Web Application ? Configuration information is specified in web.xml (Web Applications Deployment Descriptor) 36Web applications are configured via elements contained in Web application deploymentdescriptor (web.xml file). You can either manually create web.xml using a text editorof your choice or use a tool.So lets go over some configuration elements that can be specified in web.xml file. 36
  37. 37. Web Applications Deployment Descriptor (web.xml) ? Prolog ? Alias Paths ? Context and Initialization Parameters ? Event Listeners ? Filter Mappings ? Error Mappings ? Reference to Environment Entries, Resource environment entries, or Resources 37So this is the list of things that can constitute web.xml file. The most importantconfiguration information that you need to understand is what is called alias paths,which define which URL is mapped to which web components. 37
  38. 38. Web Applications Deployment Descriptor (web.xml) ? Case sensitive ? Order sensitive (in the following order) – icon, display-name, description, distributable – context-param, filter, filter-mapping – listener, servet, servlet-mapping, session-config – mime-mapping, welcome-file-list – error-page, taglib, resource-env-ref, resource-ref – security-constraint, login-config, security-role – env-entry, ejb-ref, ejb-local-ref 38Not only elements in web.xml are case sensitive, they are also order-sensitive. In otherwords, the elements in web.xml file has to be defined in a specific order that is specifiedin the Servlet specification. This slide shows the ordered list of configuration elementsif they are present in the web.xml (many of them are optional). 38
  39. 39. Prolog (of web.xml) ? Every XML document needs a prolog <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web- app_2_3.dtd"> 39Since the deployment descriptor is an XML document, it requires a prolog. The prolog ofthe web.xml file is as follows:<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD WebApplication 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> 39
  40. 40. Alias Paths (of web.xml) ? When a request is received by Servlet container, it must determine which Web component in a which web application should handle the request. It does so by mapping the URL path contained in the request to a Web component ? A URL path contains the context root and alias path – http://<host>:8080/context_root/alias_path ? Alias Path can be in the form of either – /alias-string (for servlet) or – /*.jsp (for JSP) 40When a request is received by Tomcat it must determine which Web component shouldhandle the request. It does so by mapping the URL path contained in the request to aWeb component. A URL path contains the context root and an alias path http://<host>:8080/context_root/alias_pathBefore a servlet can be accessed, the Web container must have least one alias path forthe component. The alias path must start with a / and end with a string or a wild cardexpression with an extension (*.jsp, for example). Since Web containers automaticallymap an alias path that ends with *.jsp, you do not have to specify an alias path for a JSPpage unless you wish to refer to the page by a name other than its file name. 40
  41. 41. Alias Paths (of web.xml) <servlet> <servlet-name>greeting</servlet-name> <display-name>greeting</display-name> <description>no description</description> <servlet-class>GreetingServlet</servlet-class> </servlet> <servlet> <servlet-name>response</servlet-name> <display-name>response</display-name> <description>no description</description> <servlet-class>ResponseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>greeting</servlet-name> <url-pattern>/greeting</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>response</servlet-name> <url-pattern>/response</url-pattern> </servlet-mapping> 41So in order to set up mappings of Hello application in the Web deployment descriptor,you must add “servlet” and “servlet-mapping” elements to the web.xml file. (By theway, to define an alias for a JSP page instead of a servlet, you must replace the servlet-class subelement with a jsp-file subelement in the servlet element.) 41
  42. 42. Context and Initialization Parameters (of web.xml) ? Represents application context ? Can be shared among Web components in a WAR file <web-app> ... <context-param> <param-name> javax.servlet.jsp.jstl.fmt.localizationContext </param-name> <param-value>messages.BookstoreMessages</param-value> </context-param> ... </web-app> 42The Web components in a WAR share an Java object that represents their applicationcontext, which is referred to as context object. And you can set name-value pairs to thecontext object so that all web components in the same web application can have accessto the name-value pairs that are saved in the context object. In order to initialize thename-value pairs, you add a “context-param” or “init-param element” to the web.xmlfile. The “context-param” is a sub-element of the top-level web-app element. The “init-param” is a subelement of the servlet element. This slide shows an element used todeclare a context parameter that sets the resource bundle used in the example discussedin Chapter 16 of Java WSDP Servlet tutorial: 42
  43. 43. Event Listeners (of web.xml) ? Receives servlet life-cycle events <listener> <listener-class>listeners.ContextListener</listener-class> </listener> 43You can also specify life cycle events, which we will talk about when we talk about“Servlet” later on in this course. (If you dont understand life cycle events for now, thatis fine.)Life-cycle events are only specified in the deployment descriptor if you have themcoded as part of your application. 43
  44. 44. Filter Mappings (of web.xml) ? Specify which filters are applied to a request, and in what order <filter> <filter-name>OrderFilter<filter-name> <filter-class>filters.OrderFilter<filter-class> </filter> <filter-mapping> <filter-name>OrderFilter</filter-name> <url-pattern>/receipt</url-pattern> </filter-mapping> 44This is the filter mappings. Filters are software components that intercept incomingHTTP requests and outgoing HTTP responses and perform whatever functions such ascaching, logging, compression, or transformations. And these filters can be chained andplugged during deployment time to achieve desired behavior. And which filters oughtto be plugged in and how they get chained are specified in the deployment descriptor.Filter and filter-mapping descriptors are only coded in the deployment descriptor if youhave servlet filter components. These are optional elements in the deploymentdescriptor.Again we will talk about “filter” when we talk about “advanced servlets”. And youdont really have to understand filters for now. 44
  45. 45. Error Mappings (of web.xml) ? Maps status code retURLed in an HTTP response to a Java programming language exception retURLed by any Web component and a Web resource <error-page> <exception-type>exception.OrderException</exception-type> <location>/errorpage.html</location> </error-page> 45Error mapping information is also specified in the deployment descriptor. That is, anapplication exception can be mapped into a custom error page. Or an HTTP responsecan be mapped to a Java exception, like in the example above. Otherwise, a defaulterror page will be displayed. 45
  46. 46. References (of web.xml) ? Need when web components make references to environment entries, resource environment entries, or resources such as databases ? Example: declare a reference to the data source <resource-ref> <res-ref-name>jdbc/BookDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> 46Now references. When web components make references to environment entries orresource environment entries, or resources such as databases, you can also specifyinformation on those in the deployment descriptor. And in this example, a declaration tothe data source is specified. 46
  47. 47. Example web.xml of hello2 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/ xml/ns/j2ee/web-app_2_4.xsd"> <display-name>hello2</display-name> <servlet> <display-name>GreetingServlet</display-name> <servlet-name>GreetingServlet</servlet-name> <servlet-class>servlets.GreetingServlet</servlet-class> </servlet> <servlet> <display-name>ResponseServlet</display-name> <servlet-name>ResponseServlet</servlet-name> <servlet-class>servlets.ResponseServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GreetingServlet</servlet-name> <url-pattern>/greeting</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ResponseServlet</servlet-name> <url-pattern>/response</url-pattern> </servlet-mapping> </web-app> 47So this is the complete web,xml file of the hello1 web application. Given that hello1 israther simple web application, the only thing its deployment descriptor specifies isservlet and its mapping to URNs. For example, the part in the blue color specifiesinformation about the servlet such as name and servlet classes and the part in the redcolor specify the mapping between servlet and their URNs. These URNs are the onesthat clients use when they access the web components. And when the web containerreceives the URN from a client, it knows which servlet classes to invoke by looking atthe deployment descriptors servlet mapping elements.Other elements of the deployment descriptor and how they are used are referenced infuture classes. 47
  48. 48. Passion! 48 48

×