You are on page 1of 44

Introduction

Web application

In software engineering, a web application or webapp [1] is an application that is accessed via web browser over a
network such as the Internet or an intranet. It is also a computer software application that is coded in a browser-
supported language (such as HTML, JavaScript, Java, etc.) and reliant on a common web browser to render the
application executable.

Web applications are popular due to the ever presence of a client, sometimes called a thin client. The ability to update
and maintain web applications without distributing and installing software on potentially thousands of client computers
is a key reason for their popularity. Common web applications include webmail, online retail sales, online auctions,
wikis and many other functions.

History

In earlier types of client-server computing, each application had its own client program which served as its user
interface and had to be separately installed on each user's personal computer. An upgrade to the server part of the
application would typically require an upgrade to the clients installed on each user workstation, adding to the support
cost and decreasing productivity.

In contrast, web applications use web documents written in a standard format such as HTML (and more recently
XHTML), which are supported by a variety of web browsers.

Generally, each individual web page is delivered to the client as a static document, but the sequence of pages can
provide an interactive experience, as user input is returned through web form elements embedded in the page markup.
During the session, the web browser interprets and displays the pages, and acts as the universal client for any web
application.

In 1995, Netscape introduced a client-side scripting called JavaScript, which allowed programmers to add some
dynamic elements to the user interface that ran on the client side. Until then, all the data had to be sent to the server for
processing, and the results were delivered through static HTML pages sent back to the client.

In 1996, Macromedia introduced Flash, a vector animation player that could be added to browsers as a plugin to embed
animations on the web pages. It allowed the use of a scripting language to program interactions on the client side with
no need to communicate with the server.

In 1999, the "web application" concept was introduced in the Java language in the Servlet Specification version 2.2.
[2.1?]. [1][2] At that time both JavaScript and XML had already been developed, but AJAX had not still been coined and
the XMLHttpRequest object had only been recently introduced on Internet Explorer 5 as an ActiveX object. [3]

[4]
In 2004, Web 2.0 was coined, and it was proposed to use the Web as a platform, as opposed to simply developing
applications that used Internet to communicate with the server.

In 2005, AJAX was coined, and applications like Gmail started to make their client sides more and more interactive.

Interface

Webconverger operating system provides an interface for web applications.

The web interface places very few limits on client functionality. Through Java, JavaScript, DHTML, Flash and other
technologies, application-specific methods such as drawing on the screen, playing audio, and access to the keyboard
and mouse are all possible. Many services have worked to combine all of these into a more familiar interface that
adopts the appearance of an operating system. General purpose techniques such as drag and drop are also supported by
these technologies. Web developers often use client-side scripting to add functionality, especially to create an
interactive experience that does not require page reloading (which many users find disruptive)[citation needed]. Recently,
technologies have been developed to coordinate client-side scripting with server-side technologies such as PHP. Ajax, a
web development technique using a combination of various technologies, is an example of technology which creates a
more interactive experience.

Technical considerations

A significant advantage of building web applications to support standard browser features is that they should perform
as specified regardless of the operating system or OS version installed on a given client. Rather than creating clients for
MS Windows, Mac OS X, Linux, and other operating systems, the application can be written once and deployed almost
anywhere. However, inconsistent implementations of the HTML, CSS, DOM and other browser specifications can
cause problems in web application development and support. Additionally, the ability of users to customize many of
the display settings of their browser (such as selecting different font sizes, colors, and typefaces, or disabling scripting
support) can interfere with consistent implementation of a web application.

Another approach is to use Adobe Flash or Java applets to provide some or all of the user interface. Since most web
browsers include support for these technologies (usually through plug-ins), Flash- or Java-based applications can be
implemented with much of the same ease of deployment. Because they allow the programmer greater control over the
interface, they bypass many browser-configuration issues, although incompatibilities between Java or Flash
implementations on the client can introduce different complications. Because of their architectural similarities to
traditional client-server applications, with a somewhat "thick" client, there is some dispute over whether to call systems
of this sort "web applications"; an alternative term is "Rich Internet Application" (RIA).

Structure

Applications are usually broken into logical chunks called "tiers", where every tier is assigned a role. [5] Traditional
applications consist only of 1 tier, which resides on the client machine, but web applications lend themselves to a n-
tiered approach by nature.[5] Though many variations are possible, the most common structure is the three-tiered
application.[5] In its most common form, the three tiers are called presentation, application and storage, in this order. A
web browser is the first tier (presentation), an engine using some dynamic Web content technology (such as ASP,
ASP.NET, CGI, ColdFusion, JSP/Java, PHP, Perl, Python, Ruby on Rails or Struts2) is the middle tier (application
logic), and a database is the third tier (storage).[5] The web browser sends requests to the middle tier, which services
them by making queries and updates against the database and generates a user interface.

For more complex applications, a 3-tier solution may fall short, and you may need a n-tiered approach, where the
greatest benefit is breaking the business logic, which resides on the application tier, into a more fine-grained model. [5]
For example, creating a separate business logic tier. Or adding an integration tier that separates the data tier from the
rest of tiers by providing an easy-to-use interface to access the data. [5] For example, you would access the client data by
calling a "list_clients()" function instead of making a SQL query directly against the client table on the database. That
allows to replace the underlying database without changing the other tiers.[5]

There are some who view a web application as a two-tier architecture. This can be a "smart" client that performs all the
work and queries a "dumb" server, or a "dumb" client that relies on a "smart" server. [5] The client would handle the
presentation tier, the server would have the database (storage tier), and the business logic (application tier) would be on
one of them or on both. [5] While this increases the scalability of the applications and separates the display and the
database, it still doesn't allow for true specialization of layers, so most applications will outgrow this model.[5]

Business use

An emerging strategy for application software companies is to provide web access to software previously distributed as
local applications. Depending on the type of application, it may require the development of an entirely different
browser-based interface, or merely adapting an existing application to use different presentation technology. These
programs allow the user to pay a monthly or yearly fee for use of a software application without having to install it on a
local hard drive. A company which follows this strategy is known as an application service provider (ASP), and ASPs
are currently receiving much attention in the software industry.
Writing web applications

There are many web application frameworks which facilitate rapid application development by allowing the
programmer to define a high-level description of the program. In addition, there is potential for the development of
applications on Internet operating systems, although currently there are not many viable platforms that fit this model.

The use of web application frameworks can often reduce the number of errors in a program, both by making the code
simpler, and by allowing one team to concentrate just on the framework. In applications which are exposed to constant
hacking attempts on the Internet, security-related problems caused by errors in the program are a big issue. Frameworks
may also promote the use of best practices such as GET after POST.

Brief Introduction to the Web Application development

Gone are the days of serving static HTML pages to the world. Now a days most website serves the dynamic pages
based on the user and their inputs.

This tutorial will take you through the process of developing a search engine. We will use Java Servlets

to accomplish all this.

This tutorial assumes that you are already familiar with Web concepts such as HTTP, browsers, and Web Servers as
well as the Java programming language.

What is Web Application?


First of all we learn what is Web Application? Any application that uses Web Technologies including web browsers,
web servers and Internet protocols is called Web Application.

A web application can be divided into three different layers. Presentation layer which forms the first tier of the
application, consists of web server and the web browser, which is responsible for assembling the data into presentable
format. Application layer constitutes the second tier of the application and is consisting of server side program and
scripts. Finally the third tier provides the programmable access to the databases. In an e-comm scenario when a user
(first tier), send a request to the web server, web server process the request (Second and third tier), formats the result
and finally sends the formatted results (first tier) to the client.

In this process server side scripts play a very important role of processing the users request and in the generation of
dynamic pages, based on user and its input.

In the next section we will describe the scripts used for generating the dynamic content.
Techniques used for Generating Dynamic Content

Common Gateway Interface (CGI)


For any web application high performance and timely delivery are key ingredients to competitive success.

Earlier CGI was developed to provide the server-side capability to web application. Although CGI played a major role
in the explosion of Internet, it's performance, scalability and usability issues make it less than the optimal solution. CGI
runs in a separate process separated from the web server and it requires more hardware and software resources. CGI
programs are slow because for each a new call is to the CGI program, which subsequently runs in a separate process. If
your program needs to interact with Web Server, using CGI program you can't accomplish it as CGI's separate process
can't interact with Web Server.

Scripting Languages
To solve all these problems several companies have developed server-side scripting languages. These scripts are
popular and allows developers to develop web applications that generates dynamic pages. Microsoft has developed ASP
(Active Server Pages) for IIS Server and Cold Fusion is product of Allaire. Web Server interprets these scripts when the
pages are served. These scripting languages provide good performance but imposes the portability issues as they are
limited to particular group of products or operating system.

Java Servlets
Java Servlets
eliminated all these problems. The first truly platform independent web development technique, Java Servlets breaks
down all traditional barriers giving you flexibility to run your Web Application on any Web Server.

Built from the ground up using Sun's write once run anywhere technology, Java Servlets provide excellent framework
to develop server-side application without sacrificing functionality or performance.

With Java Servlets you can finally develop your web application that can run on any platform. Java Servlets have
number of advantages over CGI and other API's. They are:

1. Platform Independence

This is very important feature of Servlets, which makes them portable across platforms and across different Web
Servers, because the Servlet API defines a standard interface between a Servlet and a Web Server.

2. Persistent:
Java Servlets are loaded once by a Web Server when it receives a request from the client and serving the
subsequent request is just a matter of creating new thread. Servlets can maintain system resources (e.g..
database connectivity etc.) between requests, thus making it easy to share resources like database connectivity.

3. Familiarity:
Servlets are written in Java Language, so anyone having some programming knowledge in Java can learn
Servlets easily. This saves saves the valuable time of learning a new programming language.

In the next section we learn about JDBC and see how to use JDBC to connect our search engine to database.
Introduction to the JDBC

Introduction

This article introduce you with JDBC and shows you how to our search engine with database.

What is JDBC?

Java Database Connectivity or JDBC for short is set of Java API's that enables the developers to create
platform and database independent applications in java. The biggest advantage of programming in Java is
its platform independence. An application written to access the MS Access database on Win 95/Win NT
platform can work on Linux against Oracle database, only by changing the name of driver, provided none of
the database calls it makes are vendor specific.

What are JDBC Drivers?

JDBC Drivers are set of classes that enables the Java application to communicate with databases. Java.sql
that ships with JDK contains various classes for using relational databases. But these classes do not provide
any implementation, only the behaviors are defined. The actual implementations are done in third-party
drivers. Third party vendors implements the java.sql.Driver interface in their database driver. A list of
currently available JDBC drivers can be found at http://java.sun.com/products/jdbc/jdbc.drivers.html

JDBC Drivers Types

Sun has defined four JDBC driver types. These are:

1. Type 1: JDBC-ODBC Bridge Driver


The first type of JDBC driver is JDBC-ODBC Bridge which provide JDBC access to any ODBC
complaint databases through ODBC drivers. Sun's JDBC-ODBC bridge is example of type 1 driver.
2. Type 2: Native -API Partly - Java Driver
Type 2 drivers are developed using native code libraries, which were originally designed for
accessing the database through C/C++. Here a thin code of Java wrap around the native code and
converts JDBC commands to DBMS-specific native calls.
3. Type 3: JDBC-Net Pure Java Driver
Type 3 drivers are a three-tier solutions. This type of driver communicates to a middleware
component which in turn connects to database and provide database connectivity.
4. Type 4: Native-Protocol Pure Java Driver
Type 4 drivers are entirely written in Java that communicate directly with vendor's database
through socket connection. Here no translation or middleware layer, are required which improves
performance tremendously.

Links to JDBC Drivers Site

1. MERANT DataDirect provides JDBC driver technology through n-tier, server-based data
connectivity and high-performance, DBMS-independent JDBC middleware.

2. MM MySQL JDBC DRIVERS - 100% pure java driver for MySQL and is distributed under the GNU
LGPL.
3. The mSQL JDBC Driver-A pure-java JDBC driver for mSQL was created and is being maintained
by George Reese from The Center for Imaginary Environments.

Connecting to the Database

JDBC Driver
In our search engine we are using MySQL database server and MM.MySQL Driver for connecting our application to
the database. MM.MySQL Driver is available at http://www.worldserver.com/mm/mysql. As stated earlier
MM.MySQL Driver is 100% pure Java Driver for MySQL and is distributed under the GNUGLP. Developers can use
this driver to make connections to MySQL server from both Java Applications and Applets. MM.MySQL Driver
provide all the JDBC features. It automatically re-connect if connection is failed. It also provide Unicode support and
support for varied character encoding.

Connecting to the Database


All the classes and interfaces of JDBC API are defined in java.sql package, so it is necessary to import java.sql.*
package in our application.

In this search engine our application communicate with database using JDBC and for making connection we are
using MM.MySQL JDBC Driver.

First of all we obtain a Connection object that represents the network connection to the database. Driver Manager
plays very important role of establishing connection. Class.forName("org.git.mm.mysql.Driver").newInstance() tells the
Driver Manager to use MM.MySQL JDBC Driver. To obtain a connection to the Database getConnection() method of
DriverManager class is used, which provides database connectivity to our search engine.

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
import java.util.*;

public class search extends HttpServlet{

//Connection object

Connection theConnection;

private String dbURL = "jdbc:mysql://10.0.0.1/javadevelopers?user=username&password=password";

//private String servletURL="/servlet";

private String servletURL="http://www.webappcabaret.com/javadevelopers";

//private String image="/images/open.gif";


private String image="http://www.roseindia.net/images/open.gif";

public void init() throws ServletException{


makeConnection();
}

public void makeConnection(){

//System.out.println("Opening db connection");

try{

Class.forName("org.gjt.mm.mysql.Driver").newInstance();
theConnection = DriverManager.getConnection(dbURL);
}
catch (Exception e)
{

// System.out.println(e.getMessage());

// System.out.println("Connected to the database");

public void destory(){


try{
theConnection.close();
}catch(Exception e){}

}
The close() method of Connection object closes the database connection.

Web application tools

20 tools for web application development

One of the main reasons we started the One Month App is because people always seem to be interested in our
development process. One of the aspects of our development process is naturally the software and tools we use. The
following is a list of the tools that we have used on this project and others, covering our full technology stack that
includes desktop, hosted and server applications. We would be very interested to hear about any tools that you use in
your development process as well.
Ruby On Rails

Rails is an open-source web application framework that is geared towards developer


happiness and sustainable productivity. This is currently our preferred framework and we have been using it for the
past couple of years.

Textmate

Textmate is a text editor for Mac OS X. I found this editor a few years ago. Soon after that, I
started seeing it used in a lot of screencasts that showcased various web development technologies. It appears like a
simple editor, but it packs a lot of useful features under the hood.

Skedit

Skedit is another text editor for Mac OS X. We'd argue that Skedit is more designer friendly than
Textmate because some of it's default features sets such as special characters helpers and remote file capability. Skedit
makes writing clean markup a breeze for a web designer.

Adobe Creative Suite

A standard suite of software for any designer, we use Adobe Creative Suite for everything from
design mockups to slicing up graphics for the web.

SnapNDrag

A very simple piece of software for Mac OS X that allows you to take screen captures and simply drag
them from the software to another piece of software (such as Adobe Photoshop). This is great when you are considering
a UI change and you want to take a quick screenshot, pull it into Photoshop, and make a quick mock-up.
Parallels

Parallels is an essential tool for allowing cross platform/browser development. We use this as we are
testing our web applications in various web browsers and platforms.

Firebug

Firebug is a plug-in for Firefox that has many web development tools. The main use that I have for it is the
inspect feature. This allows me to inspect the HTML at any time including after AJAX calls have taken place.

Basecamp

We use Basecamp to communicate and collaborate on all of our projects. It allows us to set up a schedule
with milestones and keep our messages and to-dos all in one spot.

Lighthouse

Lighthouse was developed by our friends at Active Reload. It's a


reasonably priced web based hosted tool for dealing with bug/issue tracking in software projects.

Subversion

Subversion is an open-source revision control system. I'm not really sure how we developed websites without
using subversion in the past. What I do know is that I do not want to go back. Not only does subversion keep track of
our revisions and protects us while multiple people are working on the same things, but it is also the reason that I
hardly ever open up an FTP client. Sorry Transmit, I still love you.

Warehouse

Warehouse was also developed by Active Reload. It is a web based tool that lets you
browse through your subversion repositories. Unlike Lighthouse, you can install this software on a server of your
choice.

Terminal

Terminal is my second most used application. I use it while working in my local environment as well as
interfacing with our servers. I have always liked Linux over Windows, but I felt that some of the user experience was a
bit lacking. When OSX came around with its BSD foundation a lot of us web developers started making the switch. It
has great user experience, but you can open up the terminal and feel at home.

Incubator

I found this great piece of software about 3 years ago when it was known as pyramid. We use it for all sorts
of various tasks that require organizing thoughts.

SQLEditor

I have been lightly searching for a simple Entity Relationship Diagram (ERD) tool that was native to
OSX for the past few years. This is a tool that I found when I started this project. It certainly fits what I am looking for.

MySQL

MySQL is an open-source database that we use for most of our web applications. Another great
package that we occasionally use is PostgreSQL.

MySQL Query Browser

MySQL Query Browser is a GUI application to help you take a quick glance at your queries. With features
that allow you to save and bookmark queries, as well as built-in documentation on the available features of MySQL,
this tool makes developing and working with schemas an easy process.

Linux

Linux has been my preferred server operating system for nearly a decade or as long as I've been developing
web applications. All of the tools that I use are at home on this platform.

Mongrel & Mongrel Cluster

Mongrel is a fast HTTP server for Ruby applications. Mongrel Cluster is a GemPlugin that wraps the mongrel HTTP
server and simplifies the deployment of web applications using a cluster of Mongrel servers. Mongrel Cluster will
conveniently configure and control several Mongrel servers, or groups of Mongrel servers, which are then load
balanced using a reverse proxy solution.
Nginx

Nginx is a lightweight HTTP server that we use as a reverse proxy for our Mongrel Cluster. It
also serves up our static and cached files.

Monit

Monit is a utility for managing and monitoring, processes, files, directories and devices on a UNIX system. Monit
conducts automatic maintenance and repair and can execute meaningful causal actions in error situations. We mostly
use monit to keep track of our Mongrel processes. If one fails or starts using too much ram, it will automatically restart
it.

Web appilication development using java technologies:-

Article
Developing Web Applications With JavaServer Pages 2.0
JavaServer Pages (JSP) technology, which abstracts servlets to a higher level, is an open, freely-available
specification developed by the Java Community Process (JCP) for generating dynamic content, and a key
component of the Java 2 Enterprise Edition (J2EE) specification. Many commercially available application servers
(such as BEA WebLogic, IBM WebSphere, Live JRun, and Orion) support JSP technology.

JSP technology is being used everywhere on the Web including airline reservation systems, banking systems, and
shopping. The new release, Version 2.0, is an upgrade to JSP 1.2 with several interesting new features. The
objective of JSP 2.0 is to make the task of developing dynamic Web pages easier than ever without having to learn
the Java programming language.

This article:

• Provides a fast track code intensive tutorial to get started with JSP 2.0
• Describes the new features in JSP 2.0
• Offers a flavor of the effort involved in developing applications using JSP 2.0
• Provides sample code that you can adapt for your own applications

If you are new to JSP, it might be a good idea to start directly with JSP 2.0. However, if you wish to learn about
JSP 1.2 you may want to start with this JSP tutorial.

JSP 2.0

JSP 2.0 is an upgrade to JSP 1.2 with several new interesting features that make the lives of Web application
designers and developers easier. The objective of JSP 2.0 is to make JSP easier to use than ever, and more
importantly to be used without having to learn the Java programming language itself. It simplifies the Tag APIs by
adding a new extension mechanism called SimpleTag.

In addition to several other improvements, the new key features that have been introduced in JSP 2.0 are:

1. A simple expression language (EL), which can used to easily access data from JSP pages. The expression
language simplifies writing scriptless JSP-based applications without using Java scriptlets or Java
expressions.
2. New syntax for defining reusable custom actions using JSP technology directly. The syntax is delivered
into .tag and .tagx files which can be written by developers and page authors.
3. The XML syntax has been improved substantially. The new standard filename extensions (.tagx for tag
files and .jspx for JSP files) have been added.

In this article I concentrate on the Expression Language, the simplified Tag API, and tag files. I believe existing
JSP developers will find these key features to be very interesting and useful.

Why the Jump from 1.2 to 2.0?

The version number was originally listed as 1.3 in the Java Specification Request (JSR 152). However, given that
the new features would have a deep impact on the development model of JSP applications as you will see later, the
Expert Group felt it was necessary to upgrade the major version number to 2.0 since this would reflect the impact
more appropriately. Also, the new version number will help draw the attention of developers to these new
interesting features. The good news is that all valid JSP 1.2 pages are also valid JSP 2.0 pages.

Getting Started with JSP 2.0

In order to get started with JSP 2.0, you need a JSP container that supports the JSP 2.0 specification and the Java
Servlet 2.4 specification. Luckily, Jakarta Tomcat 5.0 (Alpha release) supports the new JSP 2.0 and Servlet 2.4
specifications. Download and install Tomcat 5.0.
The JSP Expression Language

Information to be passed to JSP pages is communicated using JSP scoped attributes and request parameters. An
expression language (EL), which is designed specifically for page authors, promotes JSP scoped attributes as the
standard way to communicate information from business logic to JSP pages. Note, however, that while the EL is a
key aspect of the JSP, it is not a general purpose programming language. Rather, it is simply a data access
language, which makes it possible to easily access (and manipulate) application data without having to use
scriptlets or request-time expression values.

Prior to JSP 2.0, a page author had to use the expression <%= aName %> to access the value of a system, as in the
following example:

<someTags:aTag attribute="<%= pageContext.getAttribute("aName") %>">

or the value of a custom JavaBeans component:

<%= aCustomer.getAddress().getCountry() %>

An expression language allows a page author to access an object using a simplified syntax. For example, to access
a simple variable, you can use something like:

<someTags:aTag attribute="${aName}">

And to access a nested JavaBeans property, you would use something like:

${aCustomer.address.country}

But, you might ask, isn't this JavaScript syntax? You are absolutely right! If you've worked with JavaScript, you
will feel right at home, because the EL borrows the JavaScript syntax for accessing structured data.

Note: The Expression Language was originally developed as part of the JavaServer Pages Standard Tag Library
(JSTL) 1.0, which is a standard tag library that provides support for common, structural tasks, such as iteration and
conditionals, processing XML documents, internationalization, and database access using the Structured Query
Language (SQL). The JSTL specification is being developed by the JSR 52 expert group. For a tutorial on JSTL,
please see Faster Development with JSTL.

Accessing Application Data

You can access application data either as a property of an object, using the dot (.) operator, or a named array
element using the bracket ['name'] operator.

The expression ${data} represents the scoped variable named data. You can retrieve properties from
collections using either the dot (.) or bracket ([]) operator:

• The dot (.) operator is used to retrieve a named property. For example, the expression $
{customer.name} indicates the name property of the customer scoped variable.
• The bracket operator ([]) can be used to retrieve a named property, as in ${customer["name"]}.
The bracket operator can also be used as ${customers[0]} to refer to the first item in the customers
collection.

The expression language unifies the treatment of dot (.) and bracket ([]) operators. Therefore, $
{customer.name} is equivalent to ${customer["name"]}. As you can see, all EL expressions must be
enclosed between ${ and }.
The EL evaluates an identifier by looking up its value as an attribute using
PageContext.findAttribute(String). If the attribute is not found, null is returned.

Operators

The EL supports arithmetic, relational, and logical operators to handle the most common data manipulations. In
addition, a special operator for testing if an object is empty is provided. The operators are shown in Table 1. You
can use the empty operator to determine whether a collection or a string is empty or null. For example, $
{empty param.name} will be true only if the request parameter named param is not present. The empty
operator can be combined with the ! operator, as in the expression ${!empty param.name}, which evaluates
to true if the request parameter named param is present.

Table 1: Expression language operators


Operator Description
+ Addition
- Subtraction
* Multiplication
/ or div Division
% or mod Modulus (Remainder)
== or = Equality
!= or != Inequality
< or lt Less than
> or gt Greater than
<= or le Less than or equal to
>= or ge Greater than or equal to
&& or and Logical AND
|| or or Logical OR
! or not Boolean complement
empty Check for empty value
a ? b : c Conditional operator

Implicit Objects

In addition to operators, the EL defines implicit objects to support access to application data that is of interest to
page authors. The implicit objects defined by the EL are shown in Table 2. An example of how to use some of
these implicit objects is provided later.

Table 2: Implicit objects provided by the expression language


Implicit Object Content
applicationScope A collection of scoped variables from applications scope
cookie A collection of all cookies
header HTTP request headers as strings
headerValues HTTP request headers as collections of strings
initParam A collection of all application parameter names
The javax.servlet.jsp.PageContext object for
pageContext
the current page
pageScope A collection of all page scope objects
param A collection of all request parameters as strings
paramValues All request parameters as collections of strings
requestScope A collection of all request scope objects
sessionScope A collection of all session scope objects

EL Example

As you can tell, web page authors can use the Expression Language without having to learn Java. Code Sample 1
shows some EL expressions as well as the use of explicit objects.

Code Sample 1: ex1.jsp

<HTML>
<HEAD>
<TITLE>Expression Language Examples</TITLE>
</HEAD>

<BODY>

<H3>JSP Expression Language Examples</H3>


<P>
The following table illustrates some EL expressions and implicit objects:

<TABLE BORDER="1">
<THEAD>
<TD><B>Expression</B></TD>
<TD><B>Value</B></TD>
</THEAD>
<TR>
<TD>\${2 + 5}</TD>
<TD>${2 + 5}</TD>
</TD>
<TR>
<TD>\${4/5}</TD>
<TD>${4/5}</TD>
</TR>
<TR>
<TD>\${5 div 6}</TD>
<TD>${5 div 6}</TD>
</TR>
<TR>
<TD>\${5 mod 7}</TD>
<TD>${5 mod 7}</TD>
</TR>
<TR>
<TD>\${2 < 3}</TD>
<TD>${2 < 3}</TD>
</TR>
<TR>
<TD>\${2 gt 3}</TD>
<TD>${2 gt 3}</TD>
</TR>
<TR>
<TD>\${3.1 le 3.2}</TD>
<TD>${3.1 le 3.2}</TD>
</TR>
<TR>
<TD>\${(5 > 3) ? 5 : 3}</TD>
<TD>${(5 > 3) ? 5 : 3}</TD>
</TR>
<TR>
<TD>\${header["host"]}</TD>
<TD>${header["host"]}</TD>
</TR>
<TR>
<TD>\${header["user-agent"]}</TD>
<TD>${header["user-agent"]}</TD>
</TR>

</TABLE>

</BODY>
</HTML>

In order to run this, do the following. Here I assume that Tomcat 5.0 is installed at c:\Tomcat5.0

1. Change directory to c:\Tomcat5.0\webapps\jsp-examples


2. Create a directory and name it whatever you like, let's say jsp2-tutorial
3. Change directory to jsp2-tutorial
4. Copy the ex1.jsp from this article and save it there
5. Start the Tomcat 5 server by going to Start->Programs->Apache Tomcat 5.0->Start
Tomcat
6. In your Web browser, enter http://localhost:8080/jsp-examples/jsp2-
tutorial/ex1.jsp

You should something similar to Figure 1. It is that simple to use the Expression Language!
Figure 1: JSP Expression Language and Implicit Objects
Note: In this article, all JSP pages will be saved under c:\Tomcat5.0\webapps\jsp-examples\jsp2-
tutorial.

Fill-Out-Form Example

The implicit object, $param[var] can be used to read values from a fill-out form. Code Sample 2 shows a
simple example of a fill-out form that prompts the user to enter a name.

Code Sample 2: form.jsp

<HTML>
<HEAD>
<TITLE>Form Content</TITLE>
</HEAD>

<BODY>

<H3>Fill-out-form</H3>
<P>
<FORM action="/developer/technicalArticles/javaserverpages/JSP20/form.jsp"
method="GET">
Name = <input type="text" name="name" value="${param['name']}">
<input type="submit" value="Submit Name">
</FORM>

<P>
The Name is: ${param.name}

</BODY>
</HTML>
In this example, when the user enters a name and clicks the "Submit Name" button, the name entered will be
displayed on the same page next to "The Name is: " as shown in Figure 2.

Again, in order to run this example, simply copy form.jsp to c:\Tomcat5.0\webapps\jsp-


examples\jsp2-tutorial and request that page from a Web browser.

Figure 2: Handling forms

Developing and Using Functions

The expression language allows you to define functions that can be invoked in an expression. Functions must be
programmed as a public static method in a public class. Once the function is developed, its signature is
mapped in a Tag Library Descriptor (TLD).

To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the
method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to
integers, and returns their sum.

Code Sample 3: Compute.java

package jsp2.examples.el;

import java.util.*;

public class Compute {


public static int add(String x, String y) {
int a = 0;
int b = 0;
try {
a = Integer.parseInt(x);
b = Integer.parseInt(y);
}catch(Exception e) {}
return a + b;
}
}

Once this is successfully compiled using javac, the next step is to map the function's signature in the tag library.
Code Sample 4 shows how to map the add function to the class containing the implementation of the function and
the signature of the function. I will tell you where to add this later.

Code Sample 4: Function Descriptor


<function>
<description>add x and y</description>
<name>add</name>
<function-class>jsp2.examples.el.Compute
</function-class>
<function-signature>int
add(java.lang.String,java.lang.String)
</function-signature>
</function>

Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user
enters two numbers and when the "Add Numbers" button is clicked, the function is called to add the numbers. The
result is displayed on the same page.

Code Sample 5: math.jsp

<%@ taglib prefix="my"


uri="http://jakarta.apache.org/tomcat/jsp2-example-taglib %>

<HEAD>
<TITLE>Functions</TITLE>
</HEAD>

<BODY>

<H3>Add Numbers</H3>
<P>
<FORM action="/developer/technicalArticles/javaserverpages/JSP20/math.jsp"
method="GET">
X = <input type="text" name="x" value="${param["x"]}">
<BR>
Y = <input type="text" name="y" value="${param["y"]}">
<input type="submit" value="Add Numbers">
</FORM>

<P>
The sum is: ${my:add(param["x"],param["y"])}

</BODY>
</HTML>

To run this example:

1. Copy Compute.java and save it at: C:\Tomcat5.0\webapps\jsp-examples\WEB-


INF\classes\jsp2\examples\el
2. Compile Compute.java using javac
3. Edit the file C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-
taglib.tld and append the snippet of code in Code Sample 4 after the last </function> in the file and
before </taglib>
4. Copy math.jsp to c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial
5. Request the jsp file math.jsp from a web browser
If all goes well, you should see something similar to Figure 3.

Figure 3: Using Functions

Tag Handlers

The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With
the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has
introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways:

1. Java developers: by defining a class that implements the


javax.servlet.jsp.tagext.SimpleTag interface.
2. Page authors who do not know Java: by using tag files.

Here is an example of the first approach. Code Sample 6 shows a simple tag handler that prints This is my
first tag!.

Code Sample 6: HelloTag.java

package jsp2.examples.simpletag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
* SimpleTag handler that prints "This is my first tag!"
*/
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().getOut().write("This is my first tag!");
}
}

Once this is successfully compiled, the next step is to define a tag descriptor in a TLD. Code Sample 7 shows a
sample tag descriptor:

Code Sample 7: Tag Descriptor


<tag>
<description>Prints this is my first tag</description>
<name>hello</name>
<tag-class>jsp2.examples.simpletag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>

And finally, Code Sample 8 shows a JSP page that uses the tag I have just developed.

Code Sample 8: helloworld.jsp

<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>


<HTML>
<HEAD>
<TITLE>Simple Tag Handler</TITLE>
</HEAD>

<BODY>
<H2>Simple Tag Handler</H2>
<P>
<B>My first tag prints</B>: <mytag:hello/>
</BODY>
</HTML>

To run this example:

1. Copy HelloTag.java and save it under C:\Tomcat5.0\webapps\jsp-examples\WEB-


INF\classes\jsp2\examples\simpletag
2. Compile the HelloTag.java using javac
3. Append the tag description shown in Code Sample 7 to the end of the file:
C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld,
before </taglib>
4. Copy helloworld.jsp and save it at: c:\Tomcat5.0\webapps\jsp-examples\jsp2-
tutorial
5. Request helloworld.jsp from a web browser

If all goes well you should see something similar to Figure 4.

Figure 4: Simple Tag Handler Example

Tag File
The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that
provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action.
In other words, tag files allow JSP page authors to create reusable tag libraries using JSP syntax. The required file
extension for a tag file is .tag.

To demonstrate how easy this is, consider the tag file in Code Sample 9. That is right, this is a tag file!

Code Sample 9: greetings.tag

Hello there. How are you doing?

Once a tag file has been defined, you can write a JSP page that uses this custom action. As an example, consider
the JSP page in Code Sample 10.

Code Sample 10: chat.jsp

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>


<HTML>
<HEAD>
<TITLE>JSP 2.0 Examples - Hello World Using a Tag File</TITLE>
</HEAD>
<BODY>
<H2>Tag File Example</H2>
<P>
<B>The output of my first tag file is</B>: <tags:greetings/>
</BODY>
</HTML>

To run this example:

1. Copy the tag file, greetings.tag, and save it under c:\Tomcat5.0\webapps\jsp-


examples\WEB-INF\tags
2. Copy the JSP page, chat.jsp, and save it at c:\Tomcat5.0\webapps\jsp-examples\jsp2-
tutorial
3. Request the chat.jsp file from a Web browser

If all goes well, you should see something similar to Figure 5.

Figure 5: Simple Tag File Example


Note: What is important to notice here is that I did not need to write a TLD for the greetings tag. I just created the
tag file in a special directory, and imported it using the taglib directive, and used it!

Another Tag File Example


Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This
example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous
to the <attribute> element in the TLD; it allows for the declaration of custom action attributes.

Code Sample 11: display.tag

<%@ attribute name="color" %>


<%@ attribute name="bgcolor" %>
<%@ attribute name="title" %>
<TABLE border="0" bgcolor="${color}">
<TR>
<TD><B>${title}</B></TD>
</TR>
<TR>
<TD bgcolor="${bgcolor}">
<jsp:doBody/>
</TD>
</TR>
</TABLE>

Code Sample 12 shows a simple JSP page that uses the display tag.

Code Sample 12: newsportal.jsp

<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>


<HTML>
<HEAD>
<TITLE>Another Tag File Example</TITLE>
</HEAD>
<BODY>
<H2>News Portal: Another Tag File Example</H2>
<TABLE border="0">
<TR valign="top">
<TD>
<tags:display color="#ff0000" bgcolor="#ffc0c0"
title="Travel">
Last French Concorde Arrives in NY<br/>
Another Travel Headline<br/>
Yet Another Travel Headline<br/>
</tags:display>
</TD>
<TD>
<tags:display color="#00fc00" bgcolor="#c0ffc0"
title="Technology">
Java for in-flight entertainment<BR>
Another Technology Headline<BR>
Another Technology Headline<BR>
</tags:display>
</TD>
<TD>
<tags:display color="#ffcc11" bgcolor="#ffffcc"
title="Sports">
American Football<BR/>
NBA<BR/>
Soccer<BR/>
</tags:display>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>

To run this example:

1. Copy the file display.tag and save it under c:\Tomcat5.0\webapps\jsp-examples\WEB-


INF\tag
2. Copy the file newsportal.jsp and save it under c:\Tomcat5.0\webapps\jsp-
examples\jsp2-tutorial
3. Request the newsportal.jsp from a Web browser

Now, you should see something similar to Figure 6.

Figure 6: Using Tag File as a Template

Conclusion

JSP 2.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages. Despite the fact the
word "Java" appears in JavaServer Pages, with JSP 2.0 page authors can develop innovative dynamic Web pages
without having to learn the Java programming language. The examples shown throughout the article demonstrate
how easy it is to get started using the new features in JSP 2.0 to develop dynamic Web pages.

Develop web application with netbeans ,seam and Glassfish

In this two part series I will try to show you how easily you can build applications using NetBeans 5.5 based on seam ,
facelets , jsf and new EJB 3 standard.

I will not discuss any of framework in details as you can find detailed information about each of them in their
homepage and some other articles.
I want just show , How you can use NetBeans with some leading frameworks to build your web based applications. I
will not discuss NetBeans specific tasks in details .
I will more focus on leveraging this stuff together using NetBeans IDE.

What you will need to follow this series :

• NetBeans enterprise edition 5.5 , you will need Glassfish or JBoss to continue with this series.
check and make sure that your NetBeans has application server bundled otherwise get a copy of
glassfish from its website.
• seam 1.0.1 GA or newer.

seam distribution contain Facelets too , but i strongly suggest you get Facelets distribution separately and take a look at
its samples and very good documentation. indeed both Facelets and seam has very good documentation.

In this entry I will introduce each of this frameworks in very brief to make the series stand alone , and i will show you
how to setup the development environment and we will go with first part which is developing seam layer codes.

JBoss seam is created to leverage maximum possible feature of Java EE 5 standards like JSF and EJB3.
seam , seamlessly integrate EJB3 as a backend with JSF as presentation , meanwhile provide management of long
running process
by using JBPM . and give you ability to focus on your business logic rather than silly data providing stuff. By
leveraging Facelets helps you to do even more with seam and JSF.

To name its features I can say:

• Lesser XML, More Annotation. (please do not blame me for naming annotation and XML in one line
:-))
• it let you go with your business logic rather thinking and resolving some common issue like user
conversation state.
• seam has a more flexible context model , it has 8 context , by means of this context you can
manage your application more effective. for example a business process live in business process
context .
• Accessing each component in entire seam context with one unique name.
• Managing workplaces and conversations .
• It easily will let you develop Portlet by providing a Portlet context . we will discuss this item in latter
parts

With many more features.

But about JSF , JSF is a web framework , it is Standard and Developed under JSR 127.
Some of JSF features are as follow:

• User interface framework


• Server-side UI components
• Event model , something like desktop applications event model , but very reduced.
• Component state
• Renderers , Render Kits , for example ADF faces has a telnet render which make it possible to
render a ADF faces application for a telnet client.
• Validation
• Type conversion
• Internationalization

about Facelets , we will discuss more in next articles , but for now you should know that Facelets bring some view
related enhancement and features to JSF community .
To name some of features :
• Facelets make it possible to develop your entire web pages using your favorite page designer like
Dream weaver or Microsoft FrontPage. to achieve this feature it introduce a new attribute, jsfc ,that
make it possible to change each html element to a JSF equal component. it is similar to Tapestry
's jwcid attribute. So you can use all binding and event handling stuff of JSF and availability and
ease of use of html WYSIWYG.
• Facelets provide a template-ing features like Velocity's for JSF . it allows you to test JSF views out
of container.
• Some decoration features like what tile bring to struts community and SiteMesh ,generally, to all
java based web application.

lets start the job of creating simplest sample ;) .

I assume that you download seam and extract it in seam_home Also your NetBeans 5.5 is running and an application
server capable of containing ejb3 (Glassfish) is configured with your IDE.

for sake of simplicity we make one Library in our NetBeans IDE to make our job easier. as you know each library
could contain some jar files, etc...

Create a library name it seam and add the following jar files to it , the first
seam_home\jboss-seam.jar
seam_home\jboss-seam-ui.jar
seam_home\hibernate-all.jar
seam_home\thirdparty-all.jar

add seam library to Registeration-EJBModule and Registeration-WebModule

Switch to runtime view (CTRL+5).Extend database node , if you have no database created in your embedded derby
then create a database and create a table with following characteristics
Table Name: users
Fields :

varcahr(255) ,
username
primary key
varchar(255) , not
password
null
varcahr(255) , not
name
null

after you create this table , create a new enterprise application project by going to , file>new project>enterprise
application
name it Registeration. make sure that you have selected the Java EE 5 as j2ee version.

go to project view (CTRL+1) And select Registeration-ejbModule , right click on it and select CMP entity bean from
database...
Now you should be able to select the JDBC connection that you have made in above step and give it a package name.
click next and select users table from left column and add it to right column.
click finish.
That's it , you have your CMP ready to go.

• what we need to add to the CMP bean class in addition to its created structure
• another constructor with all the CMP fields.
• some annotation for getters , to help us in validation

final shape of users CMP will be like :


package cmps;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
*
* @author Masoud Kalali
*/
@Entity
@Name("user")
@Scope(org.jboss.seam.ScopeType.SESSION)
@Table(name="users")
public class Users implements Serializable{
private static final long serialVersionUID = 1881413500711441951L;
private String username;

private String password;

private String name;

/** Creates a new instance of Users */


public Users() {
}

public Users(String name, String password, String username)


{
this.name = name;
this.password = password;
this.username = username;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "username", nullable = false)
@Length(min=5, max=15)
public String getUsername() {
return this.username;
}

public void setUsername(String username) {


this.username = username;
}

@Column(name = "password", nullable = false)


@Length(min=5, max=15)
public String getPassword() {
return this.password;
}

public void setPassword(String password) {


this.password = password;
}
@Column(name = "name", nullable = false)
@Length(min=5, max=15)
public String getName() {
return this.name;
}

public void setName(String name) {


this.name = name;
}

we are finished with our POJO EJB :-) , now lets go and handle web layer stuff , from now we are working with seam
view layer and JSF , I will talk about Facelets later in other articles of this series.

as I said in sample scenario we have just one action , so we can use a managed bean or plain java object or whatever
that is useable here as action listener or use a stateless session bean (using session bean is what JBoss offer) so we will
use a stateless session bean to implement our action listener , it will also helps you to see how an stateless session bean
is implemented in java EE 5.
so create a session bean by using , file > new > session bean , now you can select session bean type to be stateless , and
change the package name to be sbeans
click finish , editor will open up and show you the stateless seasion bean class.
change the class body , in a way that final class looks like :

import cmps.Users;
import java.util.List;

import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.validator.Valid;
import org.jboss.seam.annotations.Factory;

import org.jboss.seam.annotations.IfInvalid;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Outcome;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.core.FacesMessages;
import org.jboss.seam.ejb.SeamInterceptor;

@Stateless
@Name("")
public class ActionBean implements sbeans.ActionLocal
{

@IfInvalid(outcome=Outcome.REDISPLAY)
public String ()
{
List existing = em.createQuery("select username from User where
username=:username")
.setParameter("username", user.getUsername())
.getResultList();
if (existing.size()==0)
{
em.persist(user);
return "success";
}
else
{
FacesMessages.instance().add("User #{user.username} already exists");
return "success";
}
}

we will need to add same method signature to our session bean local interface , so add the method signature to
ActionLocal class. it will looks like :
package sbeans;

/**
* This is the business interface for Action enterprise bean.
*/
public interface ActionLocal {
public String ();
}
now we are finished with the action , you may ask what are those annotation stuff in the session bean , so I should ask
you to take a look at seam reference or wait until next part of this series. I should say that it is a very same version of
seam sample that is implemented again in NetBeans IDE.
we are finished with EJBModule for now , lets take a look at what we will have in web module. first of all you need to
add JSF framework to web module to do this , right click on web module and select properties , go to frameworks node
and add JSF framework to the project. In web module we just have 2 JSF pages , one to , one to show the that s/he ed .
Create following JSF files ,
register.jsp same as seam sample register.jsp , used for registering purpose
registered.jsp same as seam sample registered.jsp , used for showing the user that he/she is ed

we need to add some navigation case to our faces-config.xml , so extend web module note and under configuration files
open the faces-config.xml we should add 4 navigation case to it , so right click inside the editor ,which show content of
faces-config.xml, and select add navigation rule. a dialog will open , just fill the dialog as following table show
Rule From View /register.jsp

Now right click in the editor and add 4 new navigation case , these cases will handle navigating from one view to
another.

From View From Outcome To view


/register.jsp success registered.jsp

lets code with the register.jsp , open the register.jsp in your NetBeans editor change the content to :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib prefix="s" uri="http://jboss.com/products/seam/taglib"%>
<html>
<head>
<title> New User</title>
</head>
<body>
<f:view>
<h:form>
<table border="0">
<s:validateAll>
<tr>
<td>Username</td>
<td><h:inputText id="username" value="#{user.username}" required="true" /></td>
<td> <h:message for="username"/> </td>
</tr>
<tr>
<td>Real Name</td>
<td><h:inputText id="name" value="#{user.name}" required="true" /></td>
<td> <h:message for="name"/> </td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="password" value="#{user.password}" required="true"
/></td>
<td> <h:message for="password"/> </td>
</tr>
</s:validateAll>
</table>
<h:messages globalOnly="true"/>
<h:commandButton type="submit" value="" action="#{.}"/>
</h:form>
</f:view>
</body>
</html>

No we need to create the registered.jsp which show that our user is registered. open the file in your editor
and change its content to looks like :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<title>Successfully ed New User</title>
</head>
<body>
<f:view>
Welcome, <h:outputText value="#{user.name}"/>,
you are successfully ed as <h:outputText value="#{user.username}"/>.
</f:view>
</body>
</html>

Now we are almost finished with JSf files , there are some changes that we should make in web.xml and faces-
config.xml.first open web.xml and add the following lines to it.make sure the you add them directly inside <web-app>
node.

<context-param>
<description>
</description>
<param-name>org.jboss.seam.core.init.jndiPattern</param-name>
<param-
value>java:comp/env/registration/#{ejbName}/local</param-value>
</context-param>

<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>

<ejb-local-ref>
<ejb-ref-name>registration/RegisterActionBean/local</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>sbeans.RegisterActionLocal</local>
< ejb-link>RegisterActionBean</ejb-link>
</ejb-local-ref>

Now open faces-config.xml and add the following lines to it.


<lifecycle> <phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-
listener> </lifecycle>

That's it , you are finished creating your first seam sample in netbeans , lets execute the application and see
the result. press f6 and wait until your browser opens , navigate to http://localhost:8080/Registration-
WebModule/faces/register.jsp enter some information and then press register button.

You can check whether it applied or not by switching to runtime view and checking your Users table data . you can
find complete explanation of jsp/java codes in Seam tutorial chapter 1 at :
http://docs.jboss.com/seam/1.0.0.GA/reference/en/html/tutorial.html

Getting Started with Java Web Development in Eclipse and Tomcat

(Page 1 of 4 )

This is the first part of a series of Java Web development tutorials. It is intended to warm you up by introducing two
fundamental Java web components, JSP and Servlet, and helping you prepare your development and deployment
environments for the next steps.

After you finish this tutorial, you'll understand the basic concepts of the JSP and Servlet as
web application building components and how they work behind the scenes. The relationship
between the JSP and Servlet, which puzzles many new Java web developers and is largely
ignored by many tutorials, will also be revealed. Along with this information, you will also get
full-featured environments for production level web development platforms to take your web
programming to the next level.

I assume you have some experience with Java and understand such concepts as class,
inheritance, package, classpath, etc. You should also have a good understanding of web
servers , URLs, HTTP, and HTML.

In future articles we are going to dig into JSP's and Servlet's advanced features, learn
database-driven web development, experiment with some emerging technologies like XML,
Struts, Hibernate, Spring Framework, and Ajax in the context of Java web development. In the
final tutorial, we'll put them together, using all of those techniques to build a full-blown
production level web application.

Web Application Development with JSP and XML


Part I: Fast Track JSP

Date and Time

This example contains traditional HTML and some Java code. The tag tag identifies the end of a scriptlet. When
date.jsp is requested from a web browser, you see something similar to Figure 1. Figure 1: Requesting date.jsp
Behind the ScenesWhen this page (date.jsp) is called, it will be compiled (by the JSP engine) into a java servlet. At
this point the servlet is handled by the servlet engine just like any other servlet. The servlet engine then loads the
servlet class (using a class loader) and executes it to create dynamic HTML to be sent to the browser, as shown in
Figure 2. For this example, the servlet creates a Date object and writes it as a string to the out object, which is an
output stream to the browser. Figure 2: Request/Response Flow when Calling a JSP The next time the page is
requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed, in which case it is
automatically recompiled into a servlet and executed. Scripting ElementsIn the date.jsp example the full Date class
name is used including the package name, which may become tedious. If you want to create an instance of Date
simply by using: Date today = new Date(); without having to specify the full class path use the page directive as
follows: Sample 2 :date2.jsp
Date and Time

Yet, another way of doing the same thing using the

Date and Time

Today's date is:


As you can see, the same thing can be accomplished using different tags and techniques. There are several JSP
scripting elements. Here are some conventional rules that will help you use JSP scripting elements effectively: Use to
handle declarations, expressions, or any other type of valid snippet of code. Sample 1 above is an example. Use the
page directive as in to define the scripting language. Also, it can be used to specify import statements. Here is an
example: . Use to declare variables or methods. For example: . Use to define an expression and cast the result as a
String. For example: or . Use the include directive as in to insert the contents of another file in the main JSP file. For
example: . Handling FormsOne of the most common parts of ecommerce applications is an HTML form where the
user enters some information such as name and address. Using JSP, the form's data (the information the user enters in
the form) gets stored in the request object that is sent from the browser to the JSP container. The request is processed
and the result is sent through the response object back to the browser. These two objects are implicitly available to
you. To demonstrate how to handle HTML forms using JSP, here is an example form with two fields: one for name
and the other for email. As you can see, the HTML form is defined in a JSP source file. The request.getParameter
method is being used to retrieve data from the form into variables created using JSP tags. The process.jsp page prints
either a form or the information provided by the user depending on the values of the form's fields. If the form's values
are null the form is displayed, otherwise, the information provided by the user is displayed. Note that the form is
created and being handled by code in the same JSP file. Sample 4: process.jsp

User Info Request Form

Your name:

Your email:

Process

You have provided the following info:

Name:

Email: If process.jsp is requested from a web server, you see something similar to Figure 3. Figure 3: process.jsp
loaded Enter your name and email and click on Process to submit the form for processing, and you see something
similar to Figure 4. Figure 4: Form is processed Reusable ComponentsThe above example form is simple in the sense
that there is not much code involved. When more code is involved, then it is important not to mix business logic with
front end presentation in the same file. Separating business logic from presentation permits changes to either side
without affecting the other. However, production JSP code should be limited to front end presentation. So, how do
you implement the business logic part? That is where JavaBeans come in to play. This technology is a portable,
platform-independent component model that lets developers write components and reuse them everywhere. In the
context of JSP, JavaBeans contain business logic that returns data to a script on a JSP page, which in turn formats the
data returned from the JavaBean component for display by the browser. A JSP page uses a JavaBean component by
setting and getting the properties that it provides. What are the BenefitsThere are several benefits to using JavaBeans
to augment JSP pages: Reusable components: different applications will be able to reuse the components. Separation
of business logic and presentation logic: you can change the way data is displayed without affecting business logic.
Protecting your intellectual property by keeping source code secure. Example: Using JavaBeans with JSPNow, let's
see how to modify the process.jsp example above to use JavaBeans. In the above form these are two fields: name and
email. In JavaBeans, these are called properties. So, first you write a JavaBean component with setX and getX
methods, where X is the property name. For example, if you have get and set methods: setName and getName then
you have a property known as name. Sample 5 shows a FormBean component. Good components must be able to
interoperate with other components from different vendors. Therefore, to achieve component reuse, there are two
important rules (which are imposed by the JavaBeans architecture) to follow: Your bean class must provide a
constructor with no arguments so it can be created using Beans.instantiate. Your bean class must support persistence
by implementing the interface Serializable or Externalizable. Sample 5: FormBean.java package userinfo; import
java.io.*; public class FormBean implements Serializable { private String name; private String email; public
FormBean() { name = null; email = null; } public void setName(String name) { this.name = name; } public String
getName() { return name; } public void setEmail(String email) { this.email = email; } public String getEmail()
{ return email; } } In order to use the FormBean component in the JSP file, you need to instantiate the bean
component. This is done using the tag. The next line is executed when the bean is instantiated, and used to initialize
the bean's properties. In this case, both properties (name and email) are set using a single statement. Alternatively, it
is possible to set the properties one at a time, but first you need to retrieve the form's date. Here is an example of how
you would set the name property: Once the properties have been initialized with data retrieved from the form,
property values are retrieved for presentation using in the else part, as shown in Sample 6. Sample 6: process2.jsp

User Info Request Form

Your name:

Your email:

Process

You have provided the following info:

Name:

Email: ConclusionDevelopers interested in developing quality production web applications should familiarize
themselves with technologies that are applicable not only for today's market but tomorrow's as well, namely JSP and
XML. The next article will discuss the capabilities that the JSP technology provides that are ideally suited for working
with XML; and show you how to effectively use JSP with XML. JSP and XML make an excellent combination for
web applications that share information, because JSP pages have XML support built right into them in the form of JSP
custom tag libraries. Stay tuned for more information on this in the next article in this series. coffeecup For more
informationJSP Tomcat Comparing JSP and ASP About the AuthorQusay H. Mahmoud provides Java consulting and
training services. Qusay has published dozens of articles on Java, and is the author of Distributed Programming with
Java (Manning Publications, 1999). Please click here to give us feedback.Comments?About Sun | About This Site
Newsletters | Contact Us | EmploymentHow to Buy | Licensing | Terms of Use | Privacy | Trademarks
Copyright 1994-2009 Sun Microsystems, Inc. A Sun Developer Network SiteUnless otherwise licensed, code in all
technical manuals herein (including articles, FAQs, samples) is provided under this License. XML Sun Developer
RSS Feeds&body=Check out this page on sun.com: %0A%0Ahttp%3A%2F%2Fjava.sun.com%2Fdeveloper
%2FtechnicalArticles%2Fxml%2FWebAppDev%2F" class="sharelink mailto" title="Email this page to a friend">

If you have had the opportunity to build web applications using technologies such as Common Gateway Interface
(CGI) and servlets, you are accustomed to the idea of writing a program to generate the whole page (the static and
the dynamic part) using that same program. If you are looking for a solution in which you can separate the two
parts, look no further. JavaServer Pages (JSP) are here.

JSP pages allow you to separate front-end presentation from business logic (middle and back-end tiers). It is a great
Rapid Application Development (RAD) approach to Web applications. This series of articles provides a hands-on
tutorial explaining how to develop modern Web applications for today's and tomorrow's market. This series begins
with this article, which explains the concepts and benefits of JSP technology, and then shows you how to utilize
this exciting technology, and how to create reusable components for handling forms.
The Dynamic Web

The Web has evolved from a network-based hypermedia distributed information system offering static information
to a marketplace for selling and buying goods and services. The increasingly sophisticated applications to enable
this marketplace require a technology for presenting dynamic information.

First generation solutions included CGI, which is a mechanism for running external programs through a web
server. The problem with CGI scripts is scalability; a new process is created for every request.

Second generation solutions included web server vendors providing plug-ins and APIs for their servers. The
problem is that their solutions were specific to their server products. For example, Microsoft provided Active
Server Pages (ASP) that made it easier to create dynamic content. However, their solution only worked with
Microsoft IIS or Personal Web Server. Therefore, if you wanted to use ASP you had to commit yourself to
Microsoft products and you would not be enjoying the freedom of selecting your favorite web server and operating
system!

Another second generation technology that is quite popular in enterprise computing is servlets. Servlets make it
easier to write server-side applications using Java technology. The problem with either CGI or servlets, however, is
that you have to follow the write, compile, and deploy life cycle.

JSP pages are a third generation solution that can be combined easily with some second generation solutions,
creating dynamic content, and making it easier and faster to build web-based applications that work with a variety
of other technologies: web servers, web browsers, application servers and other development tools.

JavaServer Pages (JSP)

The JSP technology is an open, freely available specification developed by Sun Microsystems as an alternative to
Microsoft's Active Server Pages (ASP) technology, and a key component of the Java 2 Enterprise Edition (J2EE)
specification. Many of the commercially available application servers (such as BEA WebLogic, IBM WebSphere,
Live JRun, Orion, and so on) already support JSP technology.

JSP versus ASP

JSP and ASP deliver similar functionality. They both use tags to allow embedded code in an HTML page, session
tracking, and database connection. Some of the trivial differences are:

• ASP pages are written in VBScript and JSP pages are written in the Java programming language.
Therefore, JSP pages are platform-independent and ASP pages are not.
• JSP pages use JavaBeans technology as the component architecture and ASP pages use ActiveX
components.

Beyond these trivial differences, there are a number of important differences that may help you in choosing a
technology for your organization:

• Speed and Scalability: Although ASP pages are cached, they are always interpreted. By contrast, JSP
pages are compiled into Java servlets and loaded into memory the first time they are called, and executed for
all subsequent calls. This gives JSP pages aspeed and scalability advantage over ASP pages.
• Extensible Tags: JSP pages have an advanced feature known as extensible tags. This mechanism enables
developers to create custom tags. In other words, extensible tags allow you to extend the JSP pages tag
syntax. You cannot do this with ASP pages.
• Freedom of Choice: Unless you install Chili!Soft ASP, ASP pages work only with Microsoft IIS and
Personal Web Server. Using ASP pages requires a commitment to Microsoft products, while JSP pages do not
tie you to any specific web server or operating system. JSP pages are becoming a widely supported standard.
For a more detailed comparison between JSP pages and ASP pages, see Comparing JSP and ASP.

Software Environment

To run JSP pages, you need a web server with a web container that conforms to JSP and servlet specifications. The
web container executes on the web server and manages the execution of all JSP pages and servlets running on that
web server. Tomcat 3.2.1 is a complete reference implementation for the Java Servlet 2.2 and JSP 1.1
specifications. Download and install binary versions of Tomcat.

To configure Tomcat:

• Set the environment variable JAVA_HOME to point to the root directory of your Java 2 Standard Edition
(J2SE) installation.
• Set the TOMCAT_HOME environment variable to point to the root directory of your Tomcat installation.
• To start Tomcat, use TOMCAT_HOME/bin/startup.bat for windows or startup.sh for UNIX.
By default, it will start listening on port 8080.
• Save your .jsp files in TOMCAT_HOME/webapps/examples/jsp and your JavaBeans classes in
TOMCAT_HOME/webapps/examples/web-inf/classes.

Note: If you work under Windows, you may get an Out of space environment error when you try to start Tomcat.
There are two ways to fix this: either change the initial memory setting of the DOS window to a value greater than
3200 OR edit the config.sys file and add the following line: SHELL=c:\PATHTO\command.com
/E:4096 /P.

How JSP Pages Work

A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page
is ".jsp" rather than ".html" or ".htm", and that tells the server that this page requires special handling that will be
accomplished by a server extension or a plug-in. Here is a simple example:

Sample 1: date.jsp

<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="ffffcc">
<CENTER>
<H2>Date and Time</H2>
<%
java.util.Date today = new java.util.Date();
out.println("Today's date is: "+today);
%>
</CENTER>
</BODY>
</HTML>

This example contains traditional HTML and some Java code. The tag <% identifies the beginning of a scriptlet,
and the %> tag identifies the end of a scriptlet. When date.jsp is requested from a web browser, you see
something similar to Figure 1.

Figure 1: Requesting date.jsp

Behind the Scenes

When this page (date.jsp) is called, it will be compiled (by the JSP engine) into a java servlet. At this point
the servlet is handled by the servlet engine just like any other servlet. The servlet engine then loads the servlet class
(using a class loader) and executes it to create dynamic HTML to be sent to the browser, as shown in Figure 2. For
this example, the servlet creates a Date object and writes it as a string to the out object, which is an output stream
to the browser.

Figure 2: Request/Response Flow when Calling a JSP

The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has
changed, in which case it is automatically recompiled into a servlet and executed.

Scripting Elements

In the date.jsp example the full Date class name is used including the package name, which may become
tedious. If you want to create an instance of Date simply by using: Date today = new Date(); without
having to specify the full class path use the page directive as follows:

Sample 2 :date2.jsp

<%@page import="java.util.*" %>


<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="ffffcc">
<CENTER>
<H2>Date and Time</H2>
<%
java.util.Date today = new java.util.Date();
out.println("Today's date is: "+today);
%>
</CENTER>
</BODY>
</HTML>

Yet, another way of doing the same thing using the <%= tag is by writing:

Sample 3:date3.jsp

<%@page import="java.util.*" %>


<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<CENTER>
<H2>Date and Time</H2>
Today's date is: <%= new Date() %>
</CENTER>
</BODY>
</HTML>

As you can see, the same thing can be accomplished using different tags and techniques. There are several JSP
scripting elements. Here are some conventional rules that will help you use JSP scripting elements effectively:

• Use <% ... %> to handle declarations, expressions, or any other type of valid snippet of code. Sample
1 above is an example.
• Use the page directive as in <%@page ... %> to define the scripting language. Also, it can be used
to specify import statements. Here is an example:
<%@page language="java" import="java.util.*" %>.
• Use <%! .... %> to declare variables or methods. For example:
<%! int x = 10; double y = 2.0; %>.
• Use <%= ... %> to define an expression and cast the result as a String. For example:
<%= a+b %> or <%= new java.util.Date() %>.
• Use the include directive as in <%@ include ... %> to insert the contents of another file in the
main JSP file. For example:
<%@include file="copyright.html" %>.

Handling Forms

One of the most common parts of ecommerce applications is an HTML form where the user enters some
information such as name and address. Using JSP, the form's data (the information the user enters in the form) gets
stored in the request object that is sent from the browser to the JSP container. The request is processed and the
result is sent through the response object back to the browser. These two objects are implicitly available to you.

To demonstrate how to handle HTML forms using JSP, here is an example form with two fields: one for name and
the other for email. As you can see, the HTML form is defined in a JSP source file. The
request.getParameter method is being used to retrieve data from the form into variables created using JSP
tags.

The process.jsp page prints either a form or the information provided by the user depending on the values of
the form's fields. If the form's values are null the form is displayed, otherwise, the information provided by the
user is displayed. Note that the form is created and being handled by code in the same JSP file.

Sample 4: process.jsp

<HTML>
<HEAD>
<TITLE>Form Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==
null && request.getParameter("email")
== null) { %>
<CENTER>
<H2>User Info Request Form</H2>
<FORM METHOD="GET"
ACTION="/developer/technicalArticles/xml/WebAppDev/process.jsp">
<P>
Your name: <input type="text" name=
"name" size=26>
<P>
Your email: <input type="text" name=
"email" size=26>
<P>
<input type="submit" value="Process">
</FORM>
</CENTER>
<% } else { %>
<%! String name, email; %>
<%
name = request.getParameter("name");
email = request.getParameter("email");
%>
<P>
<B>You have provided the following
info</B>:
<P>
<B>Name</B>: <%= name %><P>
<B>Email</B>: <%= email %>
<% } %>
</BODY>
</HTML>

If process.jsp is requested from a web server, you see something similar to Figure 3.
Figure 3: process.jsp loaded

Enter your name and email and click on Process to submit the form for processing, and you see something similar
to Figure 4.

Figure 4: Form is processed

Reusable Components

The above example form is simple in the sense that there is not much code involved. When more code is involved,
then it is important not to mix business logic with front end presentation in the same file. Separating business logic
from presentation permits changes to either side without affecting the other. However, production JSP code should
be limited to front end presentation. So, how do you implement the business logic part?

That is where JavaBeans come in to play. This technology is a portable, platform-independent component model
that lets developers write components and reuse them everywhere. In the context of JSP, JavaBeans contain
business logic that returns data to a script on a JSP page, which in turn formats the data returned from the JavaBean
component for display by the browser. A JSP page uses a JavaBean component by setting and getting the
properties that it provides.

What are the Benefits

There are several benefits to using JavaBeans to augment JSP pages:

• Reusable components: different applications will be able to reuse the components.


• Separation of business logic and presentation logic: you can change the way data is displayed without
affecting business logic.
• Protecting your intellectual property by keeping source code secure.

Example: Using JavaBeans with JSP

Now, let's see how to modify the process.jsp example above to use JavaBeans. In the above form these are
two fields: name and email. In JavaBeans, these are called properties. So, first you write a JavaBean component
with setX and getX methods, where X is the property name. For example, if you have get and set methods:
setName and getName then you have a property known as name. Sample 5 shows a FormBean component.

Good components must be able to interoperate with other components from different vendors. Therefore, to
achieve component reuse, there are two important rules (which are imposed by the JavaBeans architecture) to
follow:

1. Your bean class must provide a constructor with no arguments so it can be created using
Beans.instantiate.
2. Your bean class must support persistence by implementing the interface Serializable or
Externalizable.

Sample 5: FormBean.java

package userinfo;
import java.io.*;
public class FormBean implements Serializable {
private String name;
private String email;
public FormBean() {
name = null;
email = null;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}

In order to use the FormBean component in the JSP file, you need to instantiate the bean component. This is done
using the <jsp:useBean> tag. The next line <jsp:setProperty> is executed when the bean is instantiated,
and used to initialize the bean's properties. In this case, both properties (name and email) are set using a single
statement. Alternatively, it is possible to set the properties one at a time, but first you need to retrieve the form's
date. Here is an example of how you would set the name property:

<%! String yourname, youremail; %>


<% yourname =
request.getParameter("name"); %>
<jsp:setProperty name=
"formbean" property="name"
value="<%=yourname%>"/>

Once the properties have been initialized with data retrieved from the form, property values are retrieved for
presentation using <jsp:getProperty> in the else part, as shown in Sample 6.

Sample 6: process2.jsp

<jsp:useBean id="formbean" class=


"userinfo.FormBean"/>
<jsp:setProperty name="formbean" property=
"*"/>
<HTML>
<HEAD>
<TITLE>Form Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==null
&& request.getParameter("email") == null) { %>
<CENTER>
<H2>User Info Request Form </H2>
<form method="GET"
action="/developer/technicalArticles/xml/WebAppDev/process2.jsp">
<P>
Your name: <input type="text" name=
"name" size=27>
<p>
Your email: <input type="text" name=
"email" size=27>
<P>
<input type="submit" value="Process">
</FORM>
</CENTER>
<% } else { %>
<P>
<B>You have provided the following info</B>:
<P>
<B>Name</B>: <jsp:getProperty name=
"formbean"
property="name"/>
<P>
<B>Email</B>: <jsp:getProperty
name="formbean" property="email"/>
<% } %>
</BODY>
</HTML>

Conclusion

Developers interested in developing quality production web applications should familiarize themselves with
technologies that are applicable not only for today's market but tomorrow's as well, namely JSP and XML. The
next article will discuss the capabilities that the JSP technology provides that are ideally suited for working with
XML; and show you how to effectively use JSP with XML. JSP and XML make an excellent combination for web
applications that share information, because JSP pages have XML support built right into them in the form of JSP
custom tag libraries. Stay tuned for more information on this in the next article in this series.
Different web appilication tools

Web Application Development

ASPxGrid - 100% Native Components for ASP.NET

AireLogic publishes automatically generated client-and server-side code to any designated application server

Altova stylevision Professional - XML tool which provides conversion utilities for migration of traditional HTML Web
sites to advanced XML-based sites.

COM Express Suite (ActiveX and .NET)- Automatically generate code for N-Tier VB applications and components.

COM Express for .NET - Automatically generate code for N-Tier VB applications and components.

Cold Fusion - Web application server

ComponentOne DataObjects for .Net - Comprehensive framework for creating .NET database applications.

ComponentOne Input for .NET - Data-aware Input Controls for .NET

ComponentOne Studio Enterprise includes the complete line of .NET, ASP.NET, Mobile Device, and ActiveX products

DataDiplomat Level One - host Windows databases & be able to modify them on the Web

Dreamweaver UltraDev makes developing Web applications easy

Expresso WorkBench is a suite of software development and deployment tools

Gupta Team Developer is an integrated development environment for developing business applications
InaEmailSend - A component that can send mail via an SMTP Server.

JBuilder is the perfect tool for creating pure Java business and database applications

JClass Chart with Gold Support - Professional Graphs and Charts

JClass DesktopViews - is a comprehensive collection of client-side Java components

JClass Elements - Extensions and Enhancements for Swing

JClass HiGrid - Ideal Interface

JClass JarMaster - Package and Manage Java Classes

JClass LiveTable - Creating Professional Tables and Forms

JClass PageLayout - Professional Printing Power in Java

JClass ServerViews - High-performance Java components

JMail allows developers to quickly integrate full e-mail capabilities into Java based applications

JRun is a Java Servlet and JavaServer Pages (JSP) engine

Macromedia Dreamweaver Fireworks Studio for Web graphics design & Web site development

Macromedia Fireworks lets you design and optimize Web graphics for easy integration into your site.

Macromedia Studio MX - integrated suite of easy-to-use, powerful, and open development tools

Macromedia Web Learning Studio a Getting Started with Online Learning guide, and learning extensions.

Net Express - Ground-breaking Windows development environment

PINSuite - Collection of ambitious components for web development

PINToolbar - Create desktop like toolbars in browser

PinEdit - Add a WYSIWYG HTML editor to your browser based solutions or applications.

PrimalCode .NET IDE - Powerful .NET IDE in a small package

ProtoFax - Deliver faxes and alphanumeric pages from the Internet

R.A.D. controls suite - a collection of indispensable ASP.NET components for rapid web-development and content
management.

R.A.D. designer - browser-based componentware CMS tool for the .NET framework.

R.A.D.panelbar - component for building collapsible side-menu systems.


R.A.D.treeview - treeview component for ASP.NET

Server Express - is the platform of choice for deploying e-business and distributed applications

Simplicity for Java designs great Java applets and applications

Sitespring Server - Make your team more productive and profitable

SoftArtisans XFile is a complete HTTP client

Sybase Enterprise Application Server & Studio -- helps you build scalable Web applications

Visual DataFlex helps you create high-performance database applications

WebCombo.NET - Add advanced combo box drop down lists to your ASP.NET applications.

WebInput.NET - Powerful input control for your ASP.NET applications

WebLogic Workshop - Build service-oriented, enterprise-class Web applications and Web services

WebObjects - The incredibly powerful way to create Java Server applications

X-Win32 is an X terminal application for Windows

You might also like