SlideShare a Scribd company logo
1 of 48
Download to read offline
Web Application
                       Architecture
                 (based J2EE 1.4 Tutorial)



                                                                   1




In this session, I am going to talk about what a typical Web application
looks like. I will also show you how to build a Web application by going
through step by step guideline. Most of the contents in this presentation is
made from “Chapter 4: Web Application” tutorial section of Java WSDP.




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


                                                                              3




So 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 “web
container”. Next, we will talk about the steps you will follow to develop and
deploy 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 a
WAR file especially a meta sub-directory called WEB-INF.

A Web application has a accompanying configuration file called web.xml. This
file is referred to as the deployment descriptor of the web application and contains
all the configuration information of the application that web container needs to
know in order to deploy and run the application properly. Understanding the
web.xml file is important since you are going to have to construct web.xml file as
part of development of your web application.

Then we will go through some life-cycle operations that you can perform over
your web applications, for example, installing and deploying, listing all web
applications that are currently running on the target web container and updating,
removing, undeploying them.




                                                                                       3
Web Application &
               Web Components &
                 Web Container

                                   4




So let's understand a few terms.




                                       4
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
                                                                                                                                                         5



I talked about the container and component model of J2EE architecture during the
J2EE overview session. Under component and container architecture of J2EE, the
business logic (typically as EJB's), contents or presentations (typically as web-tier
components such as Servlet and JSP components) are captured in the form of
components and those components are then run within corresponding host execution
environment called containers. (I am using the term “components” a bit loosely here
for 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 web
components and web components can be either in the form of servlet or JSP pages
while in the EJB-tier container, the components are constructed in the form of EJB
beans.




                                                                                                                                                                5
Web Components & Container
               ?   Web components are in the form of either
                   Servlet or JSP (along with JavaBean's 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
                                                                         6



So just to repeat what I just said, web components are in the form of either servlet or
JSP pages. And web components run in a web container. And there are a few popular
web containers out there, for example, Tomcat and Resin are two most popular web
containers.

I said that containers provide host execution environment for the components providing
some system services. For web components, the web container provides several system
services, for example, receiving service requests from clients and then dispatching them
to appropriate web components, and life cycle management of your components. For
example, the web container can figure out when it is the time to create an instance of
servlet class to handle the incoming service request and when to remove the instance.




                                                                                           6
Web Application & Components
                ?   Web Application is a deployable package
                    –   Web components (Servlets and JSP's)
                    –   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)

                                                                              7




OK. We have talked a bit on what a web component is, and how web components run
in a web container. Now let's talk about a web application. A web application is
basically a collection of everything that constitutes a deployable package. The
deployable package contains multiple web components, that is, multiple servlets and
JSP pages, and static resource files such as images that are part of displayable HTML
pages, helper classes that are used by the web components, and library classes and
finally deployment descriptor (web.xml file).

A Web application is defined as a hierarchy of directories and files in a standard layout
as specified in Servlet specification. Such a hierarchy can be accessed in its unpacked
form, where each directory and file exists in the file system separately, or in a packed
form known as a Web Application Archive, or WAR file. The former format is more
useful during development, while the latter is used when you distribute your application
to the target platform.




                                                                                            7
Technologies Used
    In Web Application


                         8




.




                             8
Web Request Handling




                                                                         9




In the Java 2 platform, web components provide the dynamic extension capabilities for
a web server. Web components are either Java servlets, JSP pages, or web service
endpoints. The interaction between a web client and a web application is illustrated in
the figure of the slide.

The client sends an HTTP request to the web server. A web server that implements Java
Servlet and JavaServer Pages technology converts the request into an
HTTPServletRequest object. This object is delivered to a web component, which can
interact with JavaBeans components or a database to generate dynamic content. The
web component can then generate an HTTPServletResponse or it can pass the request to
another web component. Eventually a web component generates a
HTTPServletResponse object. The web server converts this object to an HTTP response
and returns it to the client.




                                                                                          9
Java Web Application Technologies




                                                                         10




Servlets are Java programming language classes that dynamically process requests and
construct responses. JSP pages are text-based documents that execute as servlets but
allow a more natural approach to creating static content. Although servlets and JSP
pages can be used interchangeably, each has its own strengths. Servlets are best suited
for service-oriented applications (web service endpoints are implemented as servlets)
and the control functions of a presentation-oriented application, such as dispatching
requests and handling nontextual data. JSP pages are more appropriate for generating
text-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless Markup
Language (WML), and XML.

Since the introduction of Java Servlet and JSP technology, additional Java technologies
and frameworks for building interactive web applications have been developed. These
technologies and their relationships are illustrated in the figure.




                                                                                          10
Web Application
                    Development and
                    Deployment Steps
               (using hello2 example under
                     J2EE 1.4 tutorial)


                                                                11




Now let's go over the steps needed for the development and deployment of
a web application.




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



So this is the list of steps you will follow in order to develop and deploy a web
application. First, you will write and compile the web component code. Web
component code is either servlet Java code or JSP pages and helper classes that are used
by the web components. You also need to create any static resources such as images or
HTML 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 be
either in the form of *.war file (packed form) or laid-out form of *.war file (unpacked
form) as was discussed in previous slide. A *.war file will be a compressed file with the
same layout as the build directory.

Then you will deploy the web application to the web container. We will discuss the
difference between “installation” and “deployment” later on. (There is a fine distinction
between the two.)

Once a web application is deployed, then client can access the web components through
the HTML browser. So let's go over each of these steps one by one.




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



So the first step is to write and compile web component code. Now just like any other
application development, you might want to create development directory structure that
fits your need. As we will see in the following slide, people have recommended
directory structure they found suitable for web application development. (This is only a
recommendation, of course.)

Once you create an appropriate development directory structure, you can then write
servlet or JSP along with related helper classes and other pieces. Now another thing
people find quite useful is to use ANT build tool for the development and deployment
tasks of web applications. As we will see later on, ANT is basically platform
independent make utility. And the file that contains the build instructions that ANT
uses is called build.xml file.




                                                                                           13
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

                                                                         14



In order to facilitate iterative development/deployment and also in order to keep source
code separate from compiled files, the source code for the tutorial examples is stored in
the following structure under each application directory, for example, for hello1 web
application:

? 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, images




The Ant build files (build.xml) distributed with the examples contain

*targets for creating an unpacked WAR structure in the build subdirectory of the hello1
application
*targets for copying and compiling files from the src directory to the build directory
*targets for invoking the web container's manager commands to install, reload,
remove, deploy, and undeploy applications.




                                                                                            14
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
                                                                         15



So this is an example directory structure of hello1 web application you find in the Java
WSDP. There are two servlet Java source files. And there is a web directory called web
which contains WEB-INF directory and other static resource files.

You will code each web component in the src directory.




                                                                                           15
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




                                                                           16



The 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 HTML
pages or JSP pages. And an example of image is duke that you see quite often in
various Java-related web pages.

Static resources such as image file are stored in the application's web directory.




                                                                                           16
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



                                                                        17




The next step is to create deployment descriptor, web.xml file. By the way, the name of
this file has to be web.xml file. Now web.xml file contains deployment time and
runtime instructions to the web container. For example, you can specify the URN that
clients of your web applications will use to access your web components. (We will talk
about 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 application's webWEB-INF directory.




                                                                                          17
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
                                                                                 18



Once you have all the pieces, you can create a web application. As mentioned before, a
web application is basically a deployable package that contains everything that is
needed for the deployment.

As mentioned before, a web application is either in the form or *.war file (packed) or
laid out form of the war file (unpacked). Typically a build process for the web
application involves creating “build” directory which functions as the root directory for
the compile time generated pieces such as java classes and pieces that are needed to
create *.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 and
the 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
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
                                                                         19



So this is an example of hello1 web application. Once the build process is completed
via “ant build” command, “build” directory gets created if it is not present before, and
GreetingServlet.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 directory
for creating *.war file (packed form) or can be copied over to web container (unpacked
form) for deployment.




                                                                                           19
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


                                                                                  20


Once you built a ready-to-deployable web application, you can now deploy the
application over the web container.




                                                                                       20
6. Perform Client Access to
                Web Application
                ?   From a browser, go to URL of the Web
                    application




                                                                        21



Once your web application has been deployed, then a client (typically a browser) can try
to access the web resources by specifying the appropriate URN address.




                                                                                           21
http://localhost:8080/hello1/greeting




                                                                       22



So for the hello1 example web application, a client will specify
http://localhost:8080/hello1/greeting to access the hello1 web resource.




                                                                            22
Running Web Application




                                                                       23



This is response html page that gets displayed as a result of the web resource
handling of the first HTTP request that comes from the client.




                                                                                 23
Web Application
                  Archive (*.WAR)

                                     24




OK, now let's talk about WAR file.




                                          24
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



                                                                        25



As was mentioned a couple of times already, a web application can be installed or
deployed in two different forms, either as a *.war file (packed form) or unpacked
directory 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 can
use only *.war file. And I will explain why this is the case later on.




                                                                                     25
What is *.WAR file?
                ?   Ready to deploy'able package over web
                    container
                ?   Similar to *.jar file
                ?   Contains things to be deployed
                    –   Web components (servlets or JSP's)
                    –   Server-side utility classes
                    –   Static Web presentation content (HTML, image,
                        etc)
                    –   Client-side classes (applets and utility classes)
                ?   Reflects contents in build directory
                                                                            26



So 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 such
as 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 talked
about.




                                                                                            26
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          27



Now let's talk about *.war file's directory structure a bit. The top level directory of the
war 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 and
static web resources.

The document root also contains WEB-INF directory.

Now one terminology you have heard many times (but maybe were not sure what it
exactly is) is what is called “web application context” or “context” in short. Basically
the 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 various
web 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
Directory Structure of
       *.WAR file




                                                                           28



This picture shows the directory structure of *.war file. Please note that the
“WebApplicationName” directory reflects the Document root, thus the context.




                                                                                 28
Directory Structure of
    *.WAR file




                             29



.




                                  29
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


                                                                         30



So how do you create a *.war file? There are 3 different ways to create *.war file. If
you are using an IDE, creating and deploying *.war file gets handled via one or two
clicks.

 For J2EE 1.4 tutorial sample applications, you can use “asant create-war” command
with proper build scripts. Or you can use “jar” command to create the war file. Jar
command in this case is like zip utility.




                                                                                         30
Example: Creating hello2.war via
“asant create-war” command
C:j2eetutorial14exampleswebhello2>asant create-war
Buildfile: 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
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

                                                                                      32


So 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 pieces
underneath it into the “hello2.war” file. Please don't forget the dot(.) at the end in this
example.

In the lower part of the slide, I use “jar tvf” command just to show the contents of the
newly created *.war file.




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


Now what is this WEB-INF directory? WEB-INF directory contains web.xml file, JSP
tag library descriptor files (we have not learned this yet so don't worry about it if you
don't understand), and “classes” directory that contains servlet classes and “lib”
directory that contains various jar files that could contain Java classes that are used by
the web components and their helper classes.




                                                                                             33
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 component's
                        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                                 34



Now I would like to talk about how a client can access the web service and explain
some related terms.

First “request URL” is user specified access point of a web resource. This is something
that is being passed to the web components as part of HTTP request. The typical
request 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 web
component”. 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 document
of the web application. And as a web application developer/deployer, you can choose
any name as context name for your application. The context name is specified in the
web.xml deployment descriptor.




                                                                                          34
Configuring
              Web Application via
                   web.xml

                                                                35




Now let's talk about how to configure your web application using web.xml
deployment descriptor.




                                                                           35
Configuring Web Application
                 ?   Configuration information is specified in
                     web.xml (Web Applications Deployment
                     Descriptor)




                                                                         36



Web applications are configured via elements contained in Web application deployment
descriptor (web.xml file). You can either manually create web.xml using a text editor
of your choice or use a tool.

So let's go over some configuration elements that can be specified in web.xml file.




                                                                                        36
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

                                                                          37


So this is the list of things that can constitute web.xml file. The most important
configuration information that you need to understand is what is called alias paths,
which define which URL is mapped to which web components.




                                                                                       37
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
                                                                              38



Not only elements in web.xml are case sensitive, they are also order-sensitive. In other
words, the elements in web.xml file has to be defined in a specific order that is specified
in the Servlet specification. This slide shows the ordered list of configuration elements
if they are present in the web.xml (many of them are optional).




                                                                                              38
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">




                                                                            39



Since the deployment descriptor is an XML document, it requires a prolog. The prolog of
the web.xml file is as follows:

<?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">




                                                                                      39
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)
                                                                          40



When a request is received by Tomcat it must determine which Web component 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 an alias path

     http://<host>:8080/context_root/alias_path

Before a servlet can be accessed, the Web container must have least one alias path for
the component. The alias path must start with a / and end with a string or a wild card
expression with an extension (*.jsp, for example). Since Web containers automatically
map an alias path that ends with *.jsp, you do not have to specify an alias path for a JSP
page unless you wish to refer to the page by a name other than its file name.




                                                                                             40
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>                                        41



So 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 the
way, 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
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>


                                                                            42



The Web components in a WAR share an Java object that represents their application
context, which is referred to as context object. And you can set name-value pairs to the
context object so that all web components in the same web application can have access
to the name-value pairs that are saved in the context object. In order to initialize the
name-value pairs, you add a “context-param” or “init-param element” to the web.xml
file. 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 to
declare a context parameter that sets the resource bundle used in the example discussed
in Chapter 16 of Java WSDP Servlet tutorial:




                                                                                           42
Event Listeners (of web.xml)
                  ?   Receives servlet life-cycle events

                      <listener>
                             <listener-class>listeners.ContextListener</listener-class>
                      </listener>




                                                                                   43


You can also specify life cycle events, which we will talk about when we talk about
“Servlet” later on in this course. (If you don't understand life cycle events for now, that
is fine.)

Life-cycle events are only specified in the deployment descriptor if you have them
coded as part of your application.




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


                                                                              44



This is the filter mappings. Filters are software components that intercept incoming
HTTP requests and outgoing HTTP responses and perform whatever functions such as
caching, logging, compression, or transformations. And these filters can be chained and
plugged during deployment time to achieve desired behavior. And which filters ought
to 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 you
have servlet filter components. These are optional elements in the deployment
descriptor.

Again we will talk about “filter” when we talk about “advanced servlets”. And you
don't really have to understand filters for now.




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


                                                                             45



Error mapping information is also specified in the deployment descriptor. That is, an
application exception can be mapped into a custom error page. Or an HTTP response
can be mapped to a Java exception, like in the example above. Otherwise, a default
error page will be displayed.




                                                                                        45
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>
                                                                        46


Now references. When web components make references to environment entries or
resource environment entries, or resources such as databases, you can also specify
information on those in the deployment descriptor. And in this example, a declaration to
the data source is specified.




                                                                                           46
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>                                                                  47



So this is the complete web,xml file of the hello1 web application. Given that hello1 is
rather simple web application, the only thing its deployment descriptor specifies is
servlet and its mapping to URNs. For example, the part in the blue color specifies
information about the servlet such as name and servlet classes and the part in the red
color specify the mapping between servlet and their URNs. These URNs are the ones
that clients use when they access the web components. And when the web container
receives the URN from a client, it knows which servlet classes to invoke by looking at
the deployment descriptor's servlet mapping elements.

Other elements of the deployment descriptor and how they are used are referenced in
future classes.




                                                                                                 47
Passion!


           48




                48

More Related Content

What's hot

2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-finalRohit Kelapure
 
Summer training java
Summer training javaSummer training java
Summer training javaArshit Rai
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionKelum Senanayake
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-finalRohit Kelapure
 
HowTo Build an OSGI EJB3 Server
HowTo Build an OSGI EJB3 ServerHowTo Build an OSGI EJB3 Server
HowTo Build an OSGI EJB3 Serverekkehard gentz
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJBodedns
 
Session 1 Tp1
Session 1 Tp1Session 1 Tp1
Session 1 Tp1phanleson
 
Overview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGOverview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGMarakana Inc.
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structureodedns
 
Free EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsFree EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsVirtual Nuggets
 
Java Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationJava Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationIMC Institute
 
Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Eugene Bogaart
 

What's hot (20)

J2ee architecture
J2ee architectureJ2ee architecture
J2ee architecture
 
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
2012 04-06-v2-tdp-1163-java e-evsspringshootout-final
 
Summer training java
Summer training javaSummer training java
Summer training java
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
HowTo Build an OSGI EJB3 Server
HowTo Build an OSGI EJB3 ServerHowTo Build an OSGI EJB3 Server
HowTo Build an OSGI EJB3 Server
 
EJB 2
EJB 2EJB 2
EJB 2
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJB
 
Jsf+ejb 50
Jsf+ejb 50Jsf+ejb 50
Jsf+ejb 50
 
Session 1 Tp1
Session 1 Tp1Session 1 Tp1
Session 1 Tp1
 
Overview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGOverview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUG
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Ejb (1)
Ejb (1)Ejb (1)
Ejb (1)
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structure
 
Free EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggetsFree EJB Tutorial | VirtualNuggets
Free EJB Tutorial | VirtualNuggets
 
Java Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationJava Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web Application
 
Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520
 

Similar to Web Application Architecture

Summer training java
Summer training javaSummer training java
Summer training javaArshit Rai
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overviewsohan1234
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopArun Gupta
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to strutsAnup72
 
JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6Bert Ertman
 
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Arun Gupta
 
java web framework standard.20180412
java web framework standard.20180412java web framework standard.20180412
java web framework standard.20180412FirmansyahIrma1
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical OverviewSvetlin Nakov
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts frameworks4al_com
 
Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)blahap
 

Similar to Web Application Architecture (20)

Summer training java
Summer training javaSummer training java
Summer training java
 
Ejbandjsp 200119145750
Ejbandjsp 200119145750Ejbandjsp 200119145750
Ejbandjsp 200119145750
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 Workshop
 
J2EE day 1
J2EE day 1J2EE day 1
J2EE day 1
 
Ejb and jsp
Ejb and jspEjb and jsp
Ejb and jsp
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to struts
 
JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
 
Jspx Jdc2010
Jspx Jdc2010Jspx Jdc2010
Jspx Jdc2010
 
Java J2EE
Java J2EEJava J2EE
Java J2EE
 
Frameworks in java
Frameworks in javaFrameworks in java
Frameworks in java
 
java web framework standard.20180412
java web framework standard.20180412java web framework standard.20180412
java web framework standard.20180412
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 
Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)Development of web apps based on JSF (TU Vienna)
Development of web apps based on JSF (TU Vienna)
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 

More from Abhishek Chikane

More from Abhishek Chikane (10)

MediaWiki for ALM
MediaWiki for ALMMediaWiki for ALM
MediaWiki for ALM
 
Tracking universal immunization
Tracking universal immunizationTracking universal immunization
Tracking universal immunization
 
Authentication Server
Authentication ServerAuthentication Server
Authentication Server
 
Creating Hardware Inventory
Creating Hardware InventoryCreating Hardware Inventory
Creating Hardware Inventory
 
Porting Java App To Cloud
Porting Java App To CloudPorting Java App To Cloud
Porting Java App To Cloud
 
Cloud Computing And Salesforce
Cloud Computing And SalesforceCloud Computing And Salesforce
Cloud Computing And Salesforce
 
Changing Trends In Cloud Computing
Changing Trends In Cloud ComputingChanging Trends In Cloud Computing
Changing Trends In Cloud Computing
 
Live broadcasting
Live broadcastingLive broadcasting
Live broadcasting
 
Logger implementation
Logger implementationLogger implementation
Logger implementation
 
CAPTCHA
CAPTCHACAPTCHA
CAPTCHA
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Web Application Architecture

  • 1. Web Application Architecture (based J2EE 1.4 Tutorial) 1 In this session, I am going to talk about what a typical Web application looks like. I will also show you how to build a Web application by going through step by step guideline. Most of the contents in this presentation is made from “Chapter 4: Web Application” tutorial section of Java WSDP. 1
  • 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. 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) 3 So 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 “web container”. Next, we will talk about the steps you will follow to develop and deploy 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 a WAR file especially a meta sub-directory called WEB-INF. A Web application has a accompanying configuration file called web.xml. This file is referred to as the deployment descriptor of the web application and contains all the configuration information of the application that web container needs to know in order to deploy and run the application properly. Understanding the web.xml file is important since you are going to have to construct web.xml file as part of development of your web application. Then we will go through some life-cycle operations that you can perform over your web applications, for example, installing and deploying, listing all web applications that are currently running on the target web container and updating, removing, undeploying them. 3
  • 4. Web Application & Web Components & Web Container 4 So let's understand a few terms. 4
  • 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 5 I talked about the container and component model of J2EE architecture during the J2EE overview session. Under component and container architecture of J2EE, the business logic (typically as EJB's), contents or presentations (typically as web-tier components such as Servlet and JSP components) are captured in the form of components and those components are then run within corresponding host execution environment called containers. (I am using the term “components” a bit loosely here for 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 web components and web components can be either in the form of servlet or JSP pages while in the EJB-tier container, the components are constructed in the form of EJB beans. 5
  • 6. Web Components & Container ? Web components are in the form of either Servlet or JSP (along with JavaBean's 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 6 So just to repeat what I just said, web components are in the form of either servlet or JSP pages. And web components run in a web container. And there are a few popular web containers out there, for example, Tomcat and Resin are two most popular web containers. I said that containers provide host execution environment for the components providing some system services. For web components, the web container provides several system services, for example, receiving service requests from clients and then dispatching them to appropriate web components, and life cycle management of your components. For example, the web container can figure out when it is the time to create an instance of servlet class to handle the incoming service request and when to remove the instance. 6
  • 7. Web Application & Components ? Web Application is a deployable package – Web components (Servlets and JSP's) – 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) 7 OK. We have talked a bit on what a web component is, and how web components run in a web container. Now let's talk about a web application. A web application is basically a collection of everything that constitutes a deployable package. The deployable package contains multiple web components, that is, multiple servlets and JSP pages, and static resource files such as images that are part of displayable HTML pages, helper classes that are used by the web components, and library classes and finally deployment descriptor (web.xml file). A Web application is defined as a hierarchy of directories and files in a standard layout as specified in Servlet specification. Such a hierarchy can be accessed in its unpacked form, where each directory and file exists in the file system separately, or in a packed form known as a Web Application Archive, or WAR file. The former format is more useful during development, while the latter is used when you distribute your application to the target platform. 7
  • 8. Technologies Used In Web Application 8 . 8
  • 9. Web Request Handling 9 In the Java 2 platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, or web service endpoints. The interaction between a web client and a web application is illustrated in the figure of the slide. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client. 9
  • 10. Java Web Application Technologies 10 Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Although servlets and JSP pages can be used interchangeably, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. JSP pages are more appropriate for generating text-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless Markup Language (WML), and XML. Since the introduction of Java Servlet and JSP technology, additional Java technologies and frameworks for building interactive web applications have been developed. These technologies and their relationships are illustrated in the figure. 10
  • 11. Web Application Development and Deployment Steps (using hello2 example under J2EE 1.4 tutorial) 11 Now let's go over the steps needed for the development and deployment of a web application. 11
  • 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 12 So this is the list of steps you will follow in order to develop and deploy a web application. First, you will write and compile the web component code. Web component code is either servlet Java code or JSP pages and helper classes that are used by the web components. You also need to create any static resources such as images or HTML 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 be either in the form of *.war file (packed form) or laid-out form of *.war file (unpacked form) as was discussed in previous slide. A *.war file will be a compressed file with the same layout as the build directory. Then you will deploy the web application to the web container. We will discuss the difference between “installation” and “deployment” later on. (There is a fine distinction between the two.) Once a web application is deployed, then client can access the web components through the HTML browser. So let's go over each of these steps one by one. 12
  • 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 13 So the first step is to write and compile web component code. Now just like any other application development, you might want to create development directory structure that fits your need. As we will see in the following slide, people have recommended directory structure they found suitable for web application development. (This is only a recommendation, of course.) Once you create an appropriate development directory structure, you can then write servlet or JSP along with related helper classes and other pieces. Now another thing people find quite useful is to use ANT build tool for the development and deployment tasks of web applications. As we will see later on, ANT is basically platform independent make utility. And the file that contains the build instructions that ANT uses is called build.xml file. 13
  • 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 14 In order to facilitate iterative development/deployment and also in order to keep source code separate from compiled files, the source code for the tutorial examples is stored in the following structure under each application directory, for example, for hello1 web application: ? 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, images The Ant build files (build.xml) distributed with the examples contain *targets for creating an unpacked WAR structure in the build subdirectory of the hello1 application *targets for copying and compiling files from the src directory to the build directory *targets for invoking the web container's manager commands to install, reload, remove, deploy, and undeploy applications. 14
  • 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 15 So this is an example directory structure of hello1 web application you find in the Java WSDP. There are two servlet Java source files. And there is a web directory called web which contains WEB-INF directory and other static resource files. You will code each web component in the src directory. 15
  • 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 16 The 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 HTML pages or JSP pages. And an example of image is duke that you see quite often in various Java-related web pages. Static resources such as image file are stored in the application's web directory. 16
  • 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 17 The next step is to create deployment descriptor, web.xml file. By the way, the name of this file has to be web.xml file. Now web.xml file contains deployment time and runtime instructions to the web container. For example, you can specify the URN that clients of your web applications will use to access your web components. (We will talk about 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 application's webWEB-INF directory. 17
  • 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 18 Once you have all the pieces, you can create a web application. As mentioned before, a web application is basically a deployable package that contains everything that is needed for the deployment. As mentioned before, a web application is either in the form or *.war file (packed) or laid out form of the war file (unpacked). Typically a build process for the web application involves creating “build” directory which functions as the root directory for the compile time generated pieces such as java classes and pieces that are needed to create *.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 and the 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. 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 19 So this is an example of hello1 web application. Once the build process is completed via “ant build” command, “build” directory gets created if it is not present before, and GreetingServlet.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 directory for creating *.war file (packed form) or can be copied over to web container (unpacked form) for deployment. 19
  • 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 20 Once you built a ready-to-deployable web application, you can now deploy the application over the web container. 20
  • 21. 6. Perform Client Access to Web Application ? From a browser, go to URL of the Web application 21 Once your web application has been deployed, then a client (typically a browser) can try to access the web resources by specifying the appropriate URN address. 21
  • 22. http://localhost:8080/hello1/greeting 22 So for the hello1 example web application, a client will specify http://localhost:8080/hello1/greeting to access the hello1 web resource. 22
  • 23. Running Web Application 23 This is response html page that gets displayed as a result of the web resource handling of the first HTTP request that comes from the client. 23
  • 24. Web Application Archive (*.WAR) 24 OK, now let's talk about WAR file. 24
  • 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 25 As was mentioned a couple of times already, a web application can be installed or deployed in two different forms, either as a *.war file (packed form) or unpacked directory 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 can use only *.war file. And I will explain why this is the case later on. 25
  • 26. What is *.WAR file? ? Ready to deploy'able package over web container ? Similar to *.jar file ? Contains things to be deployed – Web components (servlets or JSP's) – Server-side utility classes – Static Web presentation content (HTML, image, etc) – Client-side classes (applets and utility classes) ? Reflects contents in build directory 26 So 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 such as 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 talked about. 26
  • 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 27 Now let's talk about *.war file's directory structure a bit. The top level directory of the war 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 and static web resources. The document root also contains WEB-INF directory. Now one terminology you have heard many times (but maybe were not sure what it exactly is) is what is called “web application context” or “context” in short. Basically the 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 various web 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. Directory Structure of *.WAR file 28 This picture shows the directory structure of *.war file. Please note that the “WebApplicationName” directory reflects the Document root, thus the context. 28
  • 29. Directory Structure of *.WAR file 29 . 29
  • 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 30 So how do you create a *.war file? There are 3 different ways to create *.war file. If you are using an IDE, creating and deploying *.war file gets handled via one or two clicks. For J2EE 1.4 tutorial sample applications, you can use “asant create-war” command with proper build scripts. Or you can use “jar” command to create the war file. Jar command in this case is like zip utility. 30
  • 31. Example: Creating hello2.war via “asant create-war” command C:j2eetutorial14exampleswebhello2>asant create-war Buildfile: 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. 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 32 So 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 pieces underneath it into the “hello2.war” file. Please don't forget the dot(.) at the end in this example. In the lower part of the slide, I use “jar tvf” command just to show the contents of the newly created *.war file. 32
  • 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) 33 Now what is this WEB-INF directory? WEB-INF directory contains web.xml file, JSP tag library descriptor files (we have not learned this yet so don't worry about it if you don't understand), and “classes” directory that contains servlet classes and “lib” directory that contains various jar files that could contain Java classes that are used by the web components and their helper classes. 33
  • 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 component's 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 34 Now I would like to talk about how a client can access the web service and explain some related terms. First “request URL” is user specified access point of a web resource. This is something that is being passed to the web components as part of HTTP request. The typical request 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 web component”. 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 document of the web application. And as a web application developer/deployer, you can choose any name as context name for your application. The context name is specified in the web.xml deployment descriptor. 34
  • 35. Configuring Web Application via web.xml 35 Now let's talk about how to configure your web application using web.xml deployment descriptor. 35
  • 36. Configuring Web Application ? Configuration information is specified in web.xml (Web Applications Deployment Descriptor) 36 Web applications are configured via elements contained in Web application deployment descriptor (web.xml file). You can either manually create web.xml using a text editor of your choice or use a tool. So let's go over some configuration elements that can be specified in web.xml file. 36
  • 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 37 So this is the list of things that can constitute web.xml file. The most important configuration information that you need to understand is what is called alias paths, which define which URL is mapped to which web components. 37
  • 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 38 Not only elements in web.xml are case sensitive, they are also order-sensitive. In other words, the elements in web.xml file has to be defined in a specific order that is specified in the Servlet specification. This slide shows the ordered list of configuration elements if they are present in the web.xml (many of them are optional). 38
  • 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"> 39 Since the deployment descriptor is an XML document, it requires a prolog. The prolog of the web.xml file is as follows: <?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"> 39
  • 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) 40 When a request is received by Tomcat it must determine which Web component 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 an alias path http://<host>:8080/context_root/alias_path Before a servlet can be accessed, the Web container must have least one alias path for the component. The alias path must start with a / and end with a string or a wild card expression with an extension (*.jsp, for example). Since Web containers automatically map an alias path that ends with *.jsp, you do not have to specify an alias path for a JSP page unless you wish to refer to the page by a name other than its file name. 40
  • 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> 41 So 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 the way, 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. 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> 42 The Web components in a WAR share an Java object that represents their application context, which is referred to as context object. And you can set name-value pairs to the context object so that all web components in the same web application can have access to the name-value pairs that are saved in the context object. In order to initialize the name-value pairs, you add a “context-param” or “init-param element” to the web.xml file. 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 to declare a context parameter that sets the resource bundle used in the example discussed in Chapter 16 of Java WSDP Servlet tutorial: 42
  • 43. Event Listeners (of web.xml) ? Receives servlet life-cycle events <listener> <listener-class>listeners.ContextListener</listener-class> </listener> 43 You can also specify life cycle events, which we will talk about when we talk about “Servlet” later on in this course. (If you don't understand life cycle events for now, that is fine.) Life-cycle events are only specified in the deployment descriptor if you have them coded as part of your application. 43
  • 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> 44 This is the filter mappings. Filters are software components that intercept incoming HTTP requests and outgoing HTTP responses and perform whatever functions such as caching, logging, compression, or transformations. And these filters can be chained and plugged during deployment time to achieve desired behavior. And which filters ought to 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 you have servlet filter components. These are optional elements in the deployment descriptor. Again we will talk about “filter” when we talk about “advanced servlets”. And you don't really have to understand filters for now. 44
  • 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> 45 Error mapping information is also specified in the deployment descriptor. That is, an application exception can be mapped into a custom error page. Or an HTTP response can be mapped to a Java exception, like in the example above. Otherwise, a default error page will be displayed. 45
  • 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> 46 Now references. When web components make references to environment entries or resource environment entries, or resources such as databases, you can also specify information on those in the deployment descriptor. And in this example, a declaration to the data source is specified. 46
  • 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> 47 So this is the complete web,xml file of the hello1 web application. Given that hello1 is rather simple web application, the only thing its deployment descriptor specifies is servlet and its mapping to URNs. For example, the part in the blue color specifies information about the servlet such as name and servlet classes and the part in the red color specify the mapping between servlet and their URNs. These URNs are the ones that clients use when they access the web components. And when the web container receives the URN from a client, it knows which servlet classes to invoke by looking at the deployment descriptor's servlet mapping elements. Other elements of the deployment descriptor and how they are used are referenced in future classes. 47
  • 48. Passion! 48 48