Java Web Programming [1/9] : Introduction to Web Application

download Java Web Programming [1/9] : Introduction to Web Application

If you can't read please download the document

Transcript of Java Web Programming [1/9] : Introduction to Web Application

Slide 1

Thanisa KrauwaisayawanThanachart Numnondawww.imcinstitute.com

Module 1: Introduction to Web Application

Objectives

Evolution of Enterprise Application Frameworks

Overview: Java EE

Web application, components and Web container

Web application development and deployment steps

Building Simple Web Applications using Eclipse and Tomcat

Web Application Archive (*.WAR file)

*.WAR directory structure

WEB-INF subdirectory

Deploying WAR file to Server

Evolution of Enterprise Application Framework

Single tier

Two tier

Three tier

RPC based

Remote object based

Three tier (HTML browser and Web server)

Proprietary and standard application server

The evolution of enterprise application framework starts from single-tier mainframe based model in the beginning, moved to first phase of distributed framework, two-tier client server model, then three tier model.

Within the three-tier model, there are two communication models. First one is based on RPC (Remote Procedure Call) model in which non-object-based procedures are invoked by the client. The other model incorporates the concept of object in which remote object is accessed by the client.

When the Internet took off, the three tier model takes a very radical transformation in which HTML browser talks to a Web server, which then talks to backend database or enterprise information systems.

The next two phases are advent of the concept of application server, first, app server based on proprietary architecture and API and the next phase is where we are today with open standard based app server architecture, which is what Java EE is all about.

Single Tier (Mainframe-based)

Dumb terminals are directly connected to mainframe

Centralized model (as opposed distributed model)

Presentation, business logic, and data access are intertwined in one monolithic mainframe application

In the beginning of computing era, the model is pretty much a single tier model in which dumb terminals are directly connected to a mainframe. Here the mainframe is centralized point of computing intelligence in which presentation, business logic, and data access are all intertwined in a single monolithic mainframe application.

Two-Tier

Fat clients talking to back end database

SQL queries sent, raw data returned

Presentation,Business logic and Data Model processing logic in client application

Database

SQL request

SQL response

The next evolution phase is two-tier model. The two tier model appears along with the advent of personal computer, which was increasingly used as client platform of choice replacing dumb terminals.

In two-tier model, fat clients are talking to backend database by using some database access protocol such as SQL.

The clients are called fat clients because the clients have to maintain presentation logic, business logic, and have to have detailed understanding on data model of the backend data and how to access it.

Three-Tier (RPC based)

Thinner client: business & data model separated from presentation

Business logic and data access logic reside in middle tier server while client handles presentation

Middle tier server is now required to handle system services

Concurrency control, threading, transaction, security, persistence, multiplexing, performance, etc.

Database

SQL request

SQL response

RPC response

RPC request

The difficult to upgrade clients problem of two-tier model triggers the advent of next one, three-tier model.

The most distinguishing characteristic of three tier model is that now there is a separation between presentation logic from the other two. That is, the presentation logic is handled at the client while business and data access logic are handled at the middle tier server. In this sense, the clients of three-tier model is thinner than the ones in two-tier model. And the changes of business logic and data model can be done more flexibly than two-tier model because the only place the changes need to be reflected are at the middle-tier server not at the clients.

The three tier model, however, introduces an interesting problem of its own. Now because the middle-tier server receives service requests from many clients at the same time, the middle-tier now has to deal with various system level issues such as concurrency control, threading, transaction, security, persistence, multiplexing, performance, and so on.

Now as mentioned before, the three tier model can be further divided into RPC-based and Remote object based. In RPC based model, the clients and the middle-tier server are more tightly coupled than the object model because they have to agree upon on the implementation level (rather than interface level of remote object based model.)

Three-Tier (Remote Object based)

Business logic and data model captured in objects

Business logic and data model are now described in abstraction (interface language)

Object models used: CORBA, RMI, DCOM

Interface language in CORBA is IDL

Interface language in RMI is Java interface

Database

SQL request

SQL response

Object response

Object request

Now the next evolution is remote object-based three tier model. The key difference of this model from the three tier RPC model is that now the business logic and data model are captured in objects, which means they can be expressed in the abstract terms.

For example, the most popular remote object model is CORBA and RMI. In the case of CORBA, the business logic is abstractly expressed in IDL (Interface Definition Language) while in the case of RMI, it is in the form of Java interface type.

Three-Tier (Web Server)

Browser handles presentation logic

Browser talks Web server via HTTP protocol

Business logic and data model are handled by dynamic contents generation technologies (CGI, Servlet/JSP, ASP)

Database

SQL request

SQL response

HTML response

WEB Server

HTML request

Now a completely different three-tier model has emerged as the browser has become one of the most pervasive form of user interface at the client platform. In this model, the browser basically provides common presentation logic. And the browser and the server communicates using a standard protocol, HTTP. And the business logic and data model are captured in dynamic contents generation technologies such as CGI, servlet/JSP, or ASP. These technology components in turn talk to backend database or enterprise information system.

Proprietary and Standard Solution

Comlexity at the middle tier server still remains

Duplicate system services still need to be provided for the majority of enterprise applications

Concurrency control, Transactions

Load-balancing, Security

Resource management, Connection pooling

How to solve this problem?

Commonly shared container that handles the above system services

Proprietary versus standard based

Now the issue of middle tier still need to deal with system level issues such as concurrency control and resource management still remains the same. Furthermore, since every application has to deal with these issues, there could be duplication among the applications in the area of system services.

So what could be the solution? The solution is to come up with an architecture or framework where the common container which can be shared among all applications provide system services mentioned above.

And that is where next evolution has occurred, initially with proprietary form and later on based on an open-standard.

JavaTM 2 Platform

OptionalPackages

JavaEnterpriseEdition(Java EE)

JavaStandardEdition(Java SE)

JVM

Card VM

OptionalPackages

Personal
Profile

Foundation Profile

CDC

MIDP

CLDC

KVM

Java Platform Micro Edition(Java ME)

Java
Card

Personal
Basis Profile

Overview: Java EE

Java EE is Java SE plus a large number of serverside APIs, containers and tools.

Web Tier to Go With Java EE 6

Servlet 3.0 (JSR 315)

JavaServer Pages 2.2 (JSR 245)

Many other subsystems standardized under a single platform

EJB, JPA, JMS, JavaMail API,

The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, are verified to be well formed and in compliance with the J2EE specification, and are deployed to production, where they are run and managed by the J2EE server.

Client

Client

Client

Client

Client

Client
Tier

Enterprise
Information
Tier

Middle
Tier

Enterprise
Information
Systems (EIS):Relational
Database,Legacy
Applications,ERP Systems

Enterprise
JavaBeans

Enterprise
JavaBeans

Other Services:
JNDI, JMS,
JavaMail

Java EEApplicationServer

Web Server
JSP,
Servlets

Firewall

Java EE is End-to-End Solution

HTML/XML

I mentioned that Java EE is about building n-tier, web-based enterprise applications. That is, Java EE provides an end-to-end architecture covering from the client tier on the left side to the middle tier where Web server and Application servers reside and enterprise information tier on right side which connects the middle tier systems to the backend enterprise information systems such as relational databases, and legacy applications.

The clients can be either a full-blown Java applications or applet running inside a browser. Or more typically, the client could be a just regular HTML or XML browser communicating with the web server through HTTP. Another form of client that is getting more pervasive in an enterprise environment is 3rd-party application which performs B2B transaction with your application typically through XML. On the other side of the spectrum, the client could be wireless phones or cell phones with some kind of communication facilities. The clients could reside either behind the firewall or within the firewall. The point here is that Java EE architecture accommodate these diverse set of client types.

The middle tier typically contain web servers and application servers. In actual deployment, they could be running in a single physical platform or on multiple platforms. In some cases where reliability and scalability are important, there could be multiple web servers and application servers. The web server receives HTTP requests from the clients and handle dynamic content generation through either JSP or servlet or both. The JSP or servlet can then delegate any business logic processing to enterprise java beans running on the application server.

The key point here is that Java EE provides an end-to-end solution and deals with all these tiers with open and standard technologies.

Web Server

JNDI

J2SE

JMS

RMI/IIOP

JDBC

Database

App
Client

App Client Container

HTTP/
HTTPS

J2SE

RMI

J2SE

JNDI

JMS

RMI/IIOP

JDBC

JTA

JavaMail

JAF

JNDI

JMS

RMI/IIOP

JDBC

JTA

JavaMail

JAF

HTTP/
HTTPS

Applet Container

Applet

JSP

Servlet

EJB

Web Container

EJB Container

RMI

J2SE

Web Components & Container

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.

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 is a popular web containers

All Java EE compliant app servers (GlassFish App Server) provide web containers

Web container provides system services to Web components

Request dispatching, security, and life cycle management

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.

Components
Handle

Components/Containers Handle

Presentation

Business Logic

Concurrency

Security

Availability

Scalability

Persistence

Transaction

Life-cycle management

Management

Containers
Handle

We touched upon the roles of container and components a bit in the previous slide. Now lets compare the tasks that are being performed by containers and the ones performed by components side by side. As we talked about in the previous slide, the platform vendors provide containers while you, as application developers, develop your applications in the form of components and deploy them over the containers. As you probably will notice, many of the tasks that the containers perform are system services that a typical enterprise application would need.

First., container handles concurrency. That is, it handles concurrent access from multiple clients to your business component so that you dont have to deal with it. Each platform vendor might use different synchronization schemes to support concurrency, however. Second, containers provide built-in security framework so that implementing secure applications can be a matter of configuring some options on authentication and access control at the time of deployment not at the time of code development. Next, availability and scalability. We mentioned already that platform vendors compete in their implementations especially in the area of availability and scalability. For example, one Java EE container vendor might provide high availability by maintaining session state on a persistent storage. Another vendor might choose to implement it in a different way.

Persistence and transaction can be also handled by the container if you choose to do so. Or you might want to implement them on your own in your code, if more customized behavior is desired. Life-cycle management. Containers handle the creation and destruction of your component instances according to its own implementation scheme. Finally management and administration, some vendors might provide better management tool for managing and administering various resources in the container.

So what do you have to do as developers? Very little really. You handle only presentation and focus majority of your development effort on building business components.

Some definitions of the Web Development Process

Web Page:

simple text file consisting of text and HTML tags

Web Browser:

connects to a Web Server, sends a request for a page and receives and displays the result

interprets HTML tags to display the page exactly the way the designer wanted it to be

Web Server:

software which can respond to a Web browsers request for a page and then send that page to the browser

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)

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.

1. Create Development Tree Structure

Keep Web application source separate from compiled files

facilitate iterative development

Root directory

src: Java source of servlets and JavaBeans components

WebContent: JSP pages and HTML pages, images

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

2. Create any static resources

HTML pages

welcomePage.html

Image files that are used by HTML pages or JSP pages

Example: dukeWaving.png

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.

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

For Servlet 3.0, web.xml is optional.

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 web\WEB-INF directory.

4. Build the Web application

Build process is made of

create build directory (if it is not present) and its subdirectories

compile Java code into build/classes directory

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

Example: Hello Tree Structure

Hello

build/classes

ResultServlet.class

src

ResultServlet.java

WebContent

WEB-INF

META-INF

welcomePage.html

dukeWaving.png

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.

5. Deploy Web application

Deploy the application over deployment platform such as Sun Java System App Server or Tomcat

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

6. Perform Client Access to Web Application

From a browser, go to URN of the Web application

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.

Tool: Eclipse 3.7.2

New > Server > Apache Tomcat 7.0

New Dynamic Web Project

Choose Project Name: Hello and Specify Location

Drag image into Hello

New HTML File

welcomePage.html

welcomePage.html

Hello
Hello, my name is Duke. What's yours?



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.

http://localhost:8080/Hello/welcomePage.html

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

New Servlet

ResultServlet.java

ResultServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("username");

out.print(" Hello " + username + "");

out.close();}

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.

Test & Result

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

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.

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

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.

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

/Hello is context for Hello example

Distinguishes a Web application in a single Web container

Has to be specified as part of client URN

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

Export to Hello.WAR file

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

Directory Structure of *.WAR file

.

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)

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.

HTTP request URL & Web component URN (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 URN

http://localhost:8080/Hello/result?username=Thanisa

Context: Name of the root document of a web application Identifies a particular application on that server

/Hello is context

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.

Configuring Web Application

Configuration information is specified in web.xml (Web Applications Deployment Descriptor)

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.

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://:8080/context_root/alias_path

Alias Path can be in the form of either

/alias-string (for servlet) or

/*.jsp (for JSP)

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

: ResultServlet servlets.ResultServlet ResultServlet /result 30 welcomePage.html

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.

Try to deploy in external Tomcat

Control Panel -> Administrative Tools -> Services

http://localhost:8080/Hello/welcomePage.html

Acknowledgement

Some contents are borrowed from the presentation slides of Sang Shin, Java Technology Evangelist, Sun Microsystems, Inc.

Thank you

[email protected]/imcinstitutewww.imcinstitute.com