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 browsersupported 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] In 2004, Web 2.0 was coined, and it was proposed to use the Web as a platform, applications that used Internet to communicate with the server.
[4]

as opposed to simply developing

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

3.

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

sql. Here no translation or middleware layer.sql that ships with JDK contains various classes for using relational databases. 2. This type of driver communicates to a middleware component which in turn connects to database and provide database connectivity.html JDBC Drivers Types Sun has defined four JDBC driver types. MERANT DataDirect provides JDBC driver technology through n-tier. Type 3: JDBC-Net Pure Java Driver Type 3 drivers are a three-tier solutions. An application written to access the MS Access database on Win 95/Win NT platform can work on Linux against Oracle database. What are JDBC Drivers? JDBC Drivers are set of classes that enables the Java application to communicate with databases. 4. MM MySQL JDBC DRIVERS . Type 2: Native -API Partly Java Driver Type 2 drivers are developed using native code libraries. DBMS-independent JDBC middleware. 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. provided none of the database calls it makes are vendor specific. The biggest advantage of programming in Java is its platform independence. are required which improves performance tremendously. .drivers. only by changing the name of driver. A list of currently available JDBC drivers can be found at http://java. Links to JDBC Drivers Site 1.Introduction to the JDBC Introduction This article introduce you with JDBC and shows you how to our search engine with database. These are: 1. 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. 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. Java.com/products/jdbc/jdbc. The actual implementations are done in third-party drivers. 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.100% pure java driver for MySQL and is distributed under the GNU LGPL.sun. 2. But these classes do not provide any implementation. Third party vendors implements the java.Driver interface in their database driver. Sun's JDBC-ODBC bridge is example of type 1 driver. 3. only the behaviors are defined. server-based data connectivity and high-performance.

As stated earlier MM. Developers can use this driver to make connections to MySQL server from both Java Applications and Applets.MySQL Driver provide all the JDBC features.0. MM.net. import java. //private String image="/images/open.0.roseindia.*. import java.mm.MySQL Driver for connecting our application to the database.servlet.gif".MySQL Driver is available at http://www. First of all we obtain a Connection object that represents the network connection to the database. private String dbURL = "jdbc:mysql://10.Enumeration. 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.MySQL Driver is 100% pure Java Driver for MySQL and is distributed under the GNUGLP. In this search engine our application communicate with database using JDBC and for making connection we are using MM.http.sql.*.*. Connecting to the Database JDBC Driver In our search engine we are using MySQL database server and MM.MySQL JDBC Driver.3.sql package. so it is necessary to import java. Connecting to the Database All the classes and interfaces of JDBC API are defined in java.1/javadevelopers?user=username&password=password". import javax. .net/images/open.*.gif".git. Driver Manager plays very important role of establishing connection. import java. private String image="http://www. import java.util.* package in our application.worldserver.sql. It automatically re-connect if connection is failed.*.forName("org. It also provide Unicode support and support for varied character encoding.com/mm/mysql. private String servletURL="http://www. public void init() throws ServletException{ makeConnection(). import javax.servlet.com/javadevelopers".mysql. import java. public class search extends HttpServlet{ //Connection object Connection theConnection. MM.Driver"). //private String servletURL="/servlet". To obtain a connection to the Database getConnection() method of DriverManager class is used. which provides database connectivity to our search engine.*.util.webappcabaret.io.newInstance() tells the Driver Manager to use MM. Class.MySQL JDBC Driver.

getConnection(dbURL). hosted and server applications.getMessage()).println("Connected to the database").gjt. We would be very interested to hear about any tools that you use in your development process as well.} public void makeConnection(){ //System.mysql.out.println("Opening db connection"). One of the aspects of our development process is naturally the software and tools we use. theConnection = DriverManager. }catch(Exception e){} } The close() method of Connection object closes the database connection. The following is a list of the tools that we have used on this project and others.newInstance().out.out.close(). } // System. try{ Class.mm.forName("org. 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. } public void destory(){ try{ theConnection.Driver"). covering our full technology stack that includes desktop.println(e. . } catch (Exception e) { // System.

we use Adobe Creative Suite for everything from design mockups to slicing up graphics for the web. . This is great when you are considering a UI change and you want to take a quick screenshot. 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). 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. Soon after that. Skedit Skedit is another text editor for Mac OS X. and make a quick mock-up. It appears like a simple editor. Adobe Creative Suite A standard suite of software for any designer. pull it into Photoshop.Ruby On Rails Rails is an open-source web application framework that is geared towards developer happiness and sustainable productivity. Textmate Textmate is a text editor for Mac OS X. This is currently our preferred framework and we have been using it for the past couple of years. I found this editor a few years ago. Skedit makes writing clean markup a breeze for a web designer. I started seeing it used in a lot of screencasts that showcased various web development technologies. but it packs a lot of useful features under the hood.

Firebug Firebug is a plug-in for Firefox that has many web development tools. Subversion Subversion is an open-source revision control system. but I felt that some of the user experience was a . I still love you. We use this as we are testing our web applications in various web browsers and platforms. Sorry Transmit. The main use that I have for it is the inspect feature. I have always liked Linux over Windows. but it is also the reason that I hardly ever open up an FTP client. I'm not really sure how we developed websites without using subversion in the past. Basecamp We use Basecamp to communicate and collaborate on all of our projects.Parallels Parallels is an essential tool for allowing cross platform/browser development. you can install this software on a server of your choice. Not only does subversion keep track of our revisions and protects us while multiple people are working on the same things. Terminal Terminal is my second most used application. It allows us to set up a schedule with milestones and keep our messages and to-dos all in one spot. This allows me to inspect the HTML at any time including after AJAX calls have taken place. Lighthouse Lighthouse was developed by our friends at Active Reload. Warehouse Warehouse was also developed by Active Reload. It is a web based tool that lets you browse through your subversion repositories. What I do know is that I do not want to go back. It's a reasonably priced web based hosted tool for dealing with bug/issue tracking in software projects. I use it while working in my local environment as well as interfacing with our servers. Unlike Lighthouse.

Linux Linux has been my preferred server operating system for nearly a decade or as long as I've been developing web applications. Mongrel & Mongrel Cluster Mongrel is a fast HTTP server for Ruby applications. which are then load balanced using a reverse proxy solution. . or groups of Mongrel servers. but you can open up the terminal and feel at home. SQLEditor I have been lightly searching for a simple Entity Relationship Diagram (ERD) tool that was native to OSX for the past few years. MySQL MySQL is an open-source database that we use for most of our web applications. It has great user experience. With features that allow you to save and bookmark queries. Incubator I found this great piece of software about 3 years ago when it was known as pyramid. Mongrel Cluster will conveniently configure and control several Mongrel servers. Mongrel Cluster is a GemPlugin that wraps the mongrel HTTP server and simplifies the deployment of web applications using a cluster of Mongrel servers. When OSX came around with its BSD foundation a lot of us web developers started making the switch. this tool makes developing and working with schemas an easy process.bit lacking. as well as built-in documentation on the available features of MySQL. All of the tools that I use are at home on this platform. It certainly fits what I am looking for. Another great package that we occasionally use is PostgreSQL. This is a tool that I found when I started this project. We use it for all sorts of various tasks that require organizing thoughts. MySQL Query Browser MySQL Query Browser is a GUI application to help you take a quick glance at your queries.

Monit Monit is a utility for managing and monitoring. 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. processes.0 . files. directories and devices on a UNIX system.Nginx Nginx is a lightweight HTTP server that we use as a reverse proxy for our Mongrel Cluster. it will automatically restart it. It also serves up our static and cached files. Web appilication development using java technologies:Article Developing Web Applications With JavaServer Pages 2.

0.0 JSP 2.0 since this would reflect the impact more appropriately. the new version number will help draw the attention of developers to these new interesting features.2 you may want to start with this JSP tutorial. Many commercially available application servers (such as BEA WebLogic. .tag and .0 specification and the Java Servlet 2.2 with several new interesting features that make the lives of Web application designers and developers easier. The objective of JSP 2. New syntax for defining reusable custom actions using JSP technology directly. Why the Jump from 1.0 In order to get started with JSP 2.JavaServer Pages (JSP) technology.0. given that the new features would have a deep impact on the development model of JSP applications as you will see later. It simplifies the Tag APIs by adding a new extension mechanism called SimpleTag. The new release. which can used to easily access data from JSP pages. A simple expression language (EL). Download and install Tomcat 5. IBM WebSphere. and shopping. The good news is that all valid JSP 1. Jakarta Tomcat 5. and more importantly to be used without having to learn the Java programming language itself.0 is to make the task of developing dynamic Web pages easier than ever without having to learn the Java programming language. the simplified Tag API.0 and Servlet 2.0 are: 1.0.4 specifications. and tag files. 2. The syntax is delivered into . This article: • • • • Provides a fast track code intensive tutorial to get started with JSP 2. The expression language simplifies writing scriptless JSP-based applications without using Java scriptlets or Java expressions. which abstracts servlets to a higher level. Also. JSP 2.2 with several interesting new features. and a key component of the Java 2 Enterprise Edition (J2EE) specification. In this article I concentrate on the Expression Language. the new key features that have been introduced in JSP 2.tagx files which can be written by developers and page authors. Version 2. JSP technology is being used everywhere on the Web including airline reservation systems.2 to 2.0 Offers a flavor of the effort involved in developing applications using JSP 2. 3. The objective of JSP 2.0? The version number was originally listed as 1. The new standard filename extensions (. the Expert Group felt it was necessary to upgrade the major version number to 2.0 is to make JSP easier to use than ever. The XML syntax has been improved substantially. However.jspx for JSP files) have been added. you need a JSP container that supports the JSP 2.0 is an upgrade to JSP 1. is an upgrade to JSP 1. is an open. I believe existing JSP developers will find these key features to be very interesting and useful.0 pages. Getting Started with JSP 2.tagx for tag files and .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. banking systems.2 pages are also valid JSP 2. Luckily. and Orion) support JSP technology.3 in the Java Specification Request (JSR 152). In addition to several other improvements. However. Live JRun.0. if you wish to learn about JSP 1.0 Describes the new features in JSP 2.4 specification.0 (Alpha release) supports the new JSP 2. freely-available specification developed by the Java Community Process (JCP) for generating dynamic content.

For example. which is a standard tag library that provides support for common.) or bracket ([]) operator: • The dot (.) operator. you would use something like: ${aCustomer. The expression language unifies the treatment of dot (. The expression ${data} represents the scoped variable named data.) operator is used to retrieve a named property. you might ask.The JSP Expression Language Information to be passed to JSP pages is communicated using JSP scoped attributes and request parameters. which is designed specifically for page authors. processing XML documents.address. and database access using the Structured Query Language (SQL). You can retrieve properties from collections using either the dot (. The bracket operator can also be used as ${customers[0]} to refer to the first item in the customers collection.getAttribute("aName") %>"> or the value of a custom JavaBeans component: <%= aCustomer. using the dot (. Note. the expression $ {customer. please see Faster Development with JSTL. The JSTL specification is being developed by the JSR 52 expert group. however. as in the following example: <someTags:aTag attribute="<%= pageContext. such as iteration and conditionals. For example. .country} But. you can use something like: <someTags:aTag attribute="${aName}"> And to access a nested JavaBeans property. you will feel right at home. or a named array element using the bracket ['name'] operator. promotes JSP scoped attributes as the standard way to communicate information from business logic to JSP pages. which makes it possible to easily access (and manipulate) application data without having to use scriptlets or request-time expression values. that while the EL is a key aspect of the JSP.name} indicates the name property of the customer scoped variable. internationalization. structural tasks.name} is equivalent to ${customer["name"]}. • The bracket operator ([]) can be used to retrieve a named property. An expression language (EL). As you can see.) and bracket ([]) operators.0. Therefore. isn't this JavaScript syntax? You are absolutely right! If you've worked with JavaScript. to access a simple variable. it is simply a data access language. Note: The Expression Language was originally developed as part of the JavaServer Pages Standard Tag Library (JSTL) 1. as in ${customer["name"]}. all EL expressions must be enclosed between ${ and }. it is not a general purpose programming language. Prior to JSP 2. because the EL borrows the JavaScript syntax for accessing structured data. Rather. $ {customer.getCountry() %> An expression language allows a page author to access an object using a simplified syntax.getAddress(). a page author had to use the expression <%= aName %> to access the value of a system.0. Accessing Application Data You can access application data either as a property of an object. For a tutorial on JSTL.

the EL defines implicit objects to support access to application data that is of interest to page authors. a special operator for testing if an object is empty is provided. The implicit objects defined by the EL are shown in Table 2. Table 2: Implicit objects provided by the expression language Implicit Object Content Description Addition Subtraction Multiplication Division Modulus (Remainder) Equality Inequality Less than Greater than Less than or equal to Greater than or equal to Logical AND Logical OR Boolean complement Check for empty value Conditional operator applicationScope A collection of scoped variables from applications scope cookie A collection of all cookies .name}. If the attribute is not found. as in the expression ${!empty param. The empty operator can be combined with the ! operator. You can use the empty operator to determine whether a collection or a string is empty or null. relational. null is returned. Operators using The EL supports arithmetic.findAttribute(String). The operators are shown in Table 1. which evaluates to true if the request parameter named param is present. and logical operators to handle the most common data manipulations. $ {empty param. For example.name} will be true only if the request parameter named param is not present. In addition. An example of how to use some of these implicit objects is provided later.The EL evaluates an identifier by looking up its value as an attribute PageContext. Table 1: Expression language operators Operator + * / or div % or mod == or = != or != < or lt > or gt <= or le >= or ge && or and || or or ! or not empty a ? b : c Implicit Objects In addition to operators.

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> . Code Sample 1 shows some EL expressions as well as the use of explicit objects. web page authors can use the Expression Language without having to learn Java. Code Sample 1: ex1.servlet.jsp.PageContext object for the current page A collection of all page scope objects A collection of all request parameters as strings All request parameters as collections of strings A collection of all request scope objects A collection of all session scope objects As you can tell.header headerValues initParam pageContext pageScope param paramValues requestScope sessionScope EL Example HTTP request headers as strings HTTP request headers as collections of strings A collection of all application parameter names The javax.

4. do the following. Here I assume that Tomcat 5.jsp from this article and save it there Start the Tomcat 5 server by going to Start->Programs->Apache Tomcat 5.1 le 3.0\webapps\jsp-examples Create a directory and name it whatever you like. 6. 5.0 1.2}</TD> <TD>${3.0->Start Tomcat In your Web tutorial/ex1. 2. Change directory to c:\Tomcat5. enter http://localhost:8080/jsp-examples/jsp2- You should something similar to Figure 1.</TR> <TR> <TD>\${2 gt 3}</TD> <TD>${2 gt 3}</TD> </TR> <TR> <TD>\${3. let's say jsp2-tutorial Change directory to jsp2-tutorial Copy the ex1.jsp browser.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.0 is installed at c:\Tomcat5.1 le 3. 3. It is that simple to use the Expression Language! .

all JSP pages will be saved under c:\Tomcat5. $param[var] can be used to read values from a fill-out form.Figure 1: JSP Expression Language and Implicit Objects Note: In this article. Code Sample 2 shows a simple example of a fill-out form that prompts the user to enter a name. Fill-Out-Form Example The implicit object. Code Sample 2: form.name} </BODY> </HTML> .jsp <HTML> <HEAD> <TITLE>Form Content</TITLE> </HEAD> <BODY> <H3>Fill-out-form</H3> <P> <FORM action="/developer/technicalArticles/javaserverpages/JSP20/form.0\webapps\jsp-examples\jsp2tutorial.jsp" method="GET"> Name = <input type="text" name="name" value="${param['name']}"> <input type="submit" value="Submit Name"> </FORM> <P> The Name is: ${param.

Functions must be programmed as a public static method in a public class. 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.el. }catch(Exception e) {} return a + b. when the user enters a name and clicks the "Submit Name" button.In this example. b = Integer.parseInt(y). and returns their sum.util. Again. its signature is mapped in a Tag Library Descriptor (TLD). First we write the Java code for the method to add two numbers. in order to run this example. try { a = Integer.*. } } Once this is successfully compiled using javac. public class Compute { public static int add(String x.jsp to c:\Tomcat5. Once the function is developed. simply copy form.java package jsp2. I will tell you where to add this later.parseInt(x). Code Sample 4: Function Descriptor . Figure 2: Handling forms Developing and Using Functions The expression language allows you to define functions that can be invoked in an expression. Code Sample 3 shows a static method that accepts two Strings. String y) { int a = 0. parses them to integers. the name entered will be displayed on the same page next to "The Name is: " as shown in Figure 2. the next step is to map the function's signature in the tag library. I use a simple example to add two numbers. int b = 0. Code Sample 3: Compute. To illustrate the use of functions.0\webapps\jspexamples\jsp2-tutorial and request that page from a Web browser. import java.examples.

Code Sample 5: math.org/tomcat/jsp2-example-taglib %> <HEAD> <TITLE>Functions</TITLE> </HEAD> <BODY> <H3>Add Numbers</H3> <P> <FORM action="/developer/technicalArticles/javaserverpages/JSP20/math.jsp <%@ taglib prefix="my" uri="http://jakarta. we can write the JSP page that uses the function.param["y"])} </BODY> </HTML> To run this example: 1. the function is called to add the numbers.el.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-exampletaglib. 5. The user enters two numbers and when the "Add Numbers" button is clicked. 2.String) </function-signature> </function> Now.<function> <description>add x and y</description> <name>add</name> <function-class>jsp2.jsp from a web browser .java using javac Edit the file C:\Tomcat5.apache. 3. 4.java.String.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"]. Copy Compute.java and save it at: C:\Tomcat5.jsp to c:\Tomcat5. The result is displayed on the same page.tld and append the snippet of code in Code Sample 4 after the last </function> in the file and before </taglib> Copy math. Code Sample 5 shows a form with two fields.examples.0\webapps\jsp-examples\WEBINF\classes\jsp2\examples\el Compile Compute.lang.Compute </function-class> <function-signature>int add(java.lang.0\webapps\jsp-examples\jsp2-tutorial Request the jsp file math.

If all goes well.servlet.write("This is my first tag!"). 2. it is now feasible to develop scriptless JSP pages. import java.jsp. Java developers: by defining a javax.io. the next step is to define a tag descriptor in a TLD. To this end.jsp. With the expression language. JSP 2. /** * SimpleTag handler that prints "This is my first tag!" */ public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException.SimpleTag interface. Code Sample 7 shows a sample tag descriptor: Code Sample 7: Tag Descriptor .2 is complicated by the allowance of scriptlets in the body of tags.JspException. you should see something similar to Figure 3. Code Sample 6: HelloTag.examples.tagext.jsp.servlet.SimpleTagSupport. IOException { getJspContext().servlet. } } Once this is successfully compiled.tagext. Page authors who do not know Java: by using tag files.simpletag. Code Sample 6 shows a simple tag handler that prints This is my first tag!. class that implements the Here is an example of the first approach. import javax. however. import javax.java package jsp2.IOException. Figure 3: Using Functions Tag Handlers The APIs for classic tag handlers in JSP 1.getOut().0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: 1.

simpletag. Figure 4: Simple Tag Handler Example Tag File . Code Sample 8: helloworld.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.jsp and save it at: c:\Tomcat5.java and save it under C:\Tomcat5. Copy HelloTag. before </taglib> 4.examples.<tag> <description>Prints this is my first tag</description> <name>hello</name> <tag-class>jsp2.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld.jsp <%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib. 2.jsp from a web browser If all goes well you should see something similar to Figure 4.0\webapps\jsp-examples\WEBINF\classes\jsp2\examples\simpletag Compile the HelloTag. Request helloworld. Code Sample 8 shows a JSP page that uses the tag I have just developed.HelloTag</tag-class> <body-content>empty</body-content> </tag> And finally.java using javac Append the tag description shown in Code Sample 7 to the end of the file: C:\Tomcat5. 3. Copy helloworld.0\webapps\jsp-examples\jsp2tutorial 5.

As an example.jsp <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <HTML> <HEAD> <TITLE>JSP 2. Copy the tag file.tag.jsp. 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. and used it! Another Tag File Example .The other way of using the Simple Tag Extension is through the use of tag files.tag Hello there. Code Sample 10: chat. this is a tag file! Code Sample 9: greetings.jsp file from a Web browser If all goes well.0 Examples . tag files allow JSP page authors to create reusable tag libraries using JSP syntax. I just created the tag file in a special directory. 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.0\webapps\jspexamples\WEB-INF\tags Copy the JSP page. greetings. and save it at c:\Tomcat5. The required file extension for a tag file is . 2.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. In other words.0\webapps\jsp-examples\jsp2tutorial Request the chat. That is right. and imported it using the taglib directive. you should see something similar to Figure 5.tag. How are you doing? Once a tag file has been defined. you can write a JSP page that uses this custom action. consider the tag file in Code Sample 9. consider the JSP page in Code Sample 10. chat. and save it under c:\Tomcat5. 3. To demonstrate how easy this is.

it allows for the declaration of custom action attributes. Code Sample 12: newsportal. Code Sample 11: display.tag. display. The attribute directive is analogous to the <attribute> element in the TLD.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.0. Consider the tag file. shown in Code Sample 11.Tag files can be used as a template.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/> . This example is adapted from the panel example that comes with Tomcat 5.

0\webapps\jsp-examples\WEBINF\tag Copy the file newsportal. with JSP 2.seam and Glassfish In this two part series I will try to show you how easily you can build applications using NetBeans 5. How you can use NetBeans with some leading frameworks to build your web based applications. jsf and new EJB 3 standard. I want just show . Develop web application with netbeans .0\webapps\jsp- Request the newsportal. Copy the file display. 2. facelets . Figure 6: Using Tag File as a Template Conclusion JSP 2.5 based on seam .jsp from a Web browser Now. 3. The examples shown throughout the article demonstrate how easy it is to get started using the new features in JSP 2.0 page authors can develop innovative dynamic Web pages without having to learn the Java programming language. 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.jsp examples\jsp2-tutorial and save it under c:\Tomcat5. you should see something similar to Figure 6. Despite the fact the word "Java" appears in JavaServer Pages. I .tag and save it under c:\Tomcat5.</tags:display> </TD> </TR> </TABLE> </BODY> </HTML> To run this example: 1.0 to develop dynamic Web pages.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages.

5 . Managing workplaces and conversations . By helps you to do even more with seam and JSF. Accessing each component in entire seam context with one unique name. JSF is a web framework . To name some of features : .will not discuss NetBeans specific I will more focus on leveraging this stuff together using NetBeans IDE. seamlessly integrate running by using JBPM . Render Kits . but very reduced.1 GA or newer.0. meanwhile provide management of long process you ability to focus on your business logic rather than silly data providing stuff. we will discuss this item in latter parts With many more features. (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. for example a business process live in business process context . for example ADF faces has a telnet render which make it possible to render a ADF faces application for a telnet client. seam 1. EJB3 as a backend with JSF as presentation . It easily will let you develop Portlet by providing a Portlet context . and give leveraging Facelets leverage maximum possible feature of Java EE 5 standards like JSF and EJB3. What you will need to follow this series : tasks in details . Component state Renderers . indeed both Facelets and seam has very good documentation. it has 8 context . More Annotation. we will discuss more in next articles . you will need Glassfish or JBoss to continue with this series. but for now you should know that Facelets bring some view related enhancement and features to JSF community . check and make sure that your NetBeans has application server bundled otherwise get a copy of glassfish from its website. • • NetBeans enterprise edition 5. To name its features I can say: • • • • • • Lesser XML. it is Some of JSF features are as follow: Standard and Developed under JSR 127. In this entry I will introduce each of this frameworks in very brief to make the series stand alone . Validation Type conversion Internationalization about Facelets . and i will show you how to setup the development environment and we will go with first part which is developing seam layer codes. but i strongly suggest you get Facelets distribution separately and take a look at its samples and very good documentation. something like desktop applications event model . But about JSF . • • • • • • • • User interface framework Server-side UI components Event model . seam has a more flexible context model . JBoss seam is created to seam . seam distribution contain Facelets too . by means of this context you can manage your application more effective.

for sake of simplicity we make one Library in our NetBeans IDE to make our job easier. some annotation for getters .5 is running and an application server capable of containing ejb3 (Glassfish) is configured with your IDE..generally. • • • what we need to add to the CMP bean class in addition to its created structure another constructor with all the CMP fields. the first add seam library to Registeration-EJBModule and Registeration-WebModule Switch to runtime view (CTRL+5).• • • Facelets make it possible to develop your entire web pages using your favorite page designer like Dream weaver or Microsoft FrontPage. username password name varchar(255) .jar seam_home\thirdparty-all. Create a library name seam_home\jboss-seam.Extend database node .jar it seam and add the following jar files to it ... not null varcahr(255) .. not null after you create this table . it is similar to Tapestry 's jwcid attribute. That's it . Now you should be able to select the JDBC connection that you have made in above step and give it a package name. go to project view (CTRL+1) And select Registeration-ejbModule . jsfc . right click on it and select CMP entity bean from database. to all java based web application. Some decoration features like what tile bring to struts community and SiteMesh . as you know each library could contain some jar files. etc. you have your CMP ready to go. Facelets provide a template-ing features like Velocity's for JSF . to help us in validation final shape of users CMP will be like : .) . So you can use all binding and event handling stuff of JSF and availability and ease of use of html WYSIWYG. lets start the job of creating simplest sample . it allows you to test JSF views out of container. click next and select users table from left column and add it to right column.jar seam_home\hibernate-all. 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) primary key . make sure that you have selected the Java EE 5 as j2ee version. create a new enterprise application project by going to . file>new project>enterprise application name it Registeration.jar seam_home\jboss-seam-ui.that make it possible to change each html element to a JSF equal component. I assume that you download seam and extract it in seam_home Also your NetBeans 5. to achieve this feature it introduce a new attribute. click finish.

String username) { this.seam. import org. /** * * @author Masoud Kalali */ @Entity @Name("user") @Scope(org.Serializable.name = name.password = password.Entity. import org. import org.persistence.username = username.username. } public void setPassword(String password) { this.annotations. /** Creates a new instance of Users */ public Users() { } public Users(String name.persistence. javax.annotations.AUTO) @Column(name = "username".password = password. } public void setUsername(String username) { this.persistence.package cmps.io.Id.hibernate.Name.jboss. javax.Length.GeneratedValue. nullable = false) @Length(min=5. javax. this.username = username. nullable = false) @Length(min=5.persistence. max=15) public String getUsername() { return this.password.persistence.Table.SESSION) @Table(name="users") public class Users implements Serializable{ private static final long serialVersionUID = 1881413500711441951L.validator.NotNull.ScopeType.seam. private String password.jboss.jboss. } . javax. this. import org.Scope.seam.persistence.GenerationType. max=15) public String getPassword() { return this. String password. private String username.hibernate. } @Id @GeneratedValue(strategy = GenerationType. } @Column(name = "password".Column. private String name. javax. import import import import import import import java.validator. javax.

Name. 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 . return "success".jboss.seam.IfInvalid.persistence. org.seam.setParameter("username". as I said in sample scenario we have just one action . javax. org.ActionLocal { @IfInvalid(outcome=Outcome. import import import import import import import javax.Factory. user.DataModel. from now we are working with seam view layer and JSF . javax. and change the package name to be sbeans click finish .jboss.@Column(name = "name".annotations. org.seam.jboss.getUsername()) .persistence.annotations.FacesMessages. org. file > new > session bean .hibernate.size()==0) { em.Stateless.Valid.annotations.seam.jboss. now lets go and handle web layer stuff .ejb.getResultList().context. . org.name.annotations.ejb.jboss. import import import import import import import org. org. nullable = false) @Length(min=5.FacesContext.util.jboss.annotations. it will also helps you to see how an stateless session bean is implemented in java EE 5.PersistenceContext. javax. javax.add("User #{user. max=15) public String getName() { return this. editor will open up and show you the stateless seasion bean class.name = name.jboss. so create a session bean by using .core.seam.Outcome. change the class body .application. if (existing.faces.faces.In. } else { FacesMessages. I will talk about Facelets later in other articles of this series.annotations.seam.persist(user).validator.FacesMessage. org.seam. org.REDISPLAY) public String () { List existing = em. now you can select session bean type to be stateless .datamodel. @Stateless @Name("") public class ActionBean implements sbeans.Users.username} already exists").instance().seam.SeamInterceptor. in a way that final class looks like : import cmps.jboss. } public void setName(String name) { this. } } we are finished with our POJO EJB :-) .List.EntityManager. import java.createQuery("select username from User where username=:username") .

xml . one to show the that s/he ed .which show content of faces-config. right click on web module and select properties . these cases will handle navigating from one view to another. /** * This is the business interface for Action enterprise bean. you may ask what are those annotation stuff in the session bean . we are finished with EJBModule for now . lets take a look at what we will have in web module. Create following JSF files .return "success".com/jsf/html" prefix="h" %> <%@ taglib uri="http://java. so right click inside the editor .jsp . used for registering purpose same as seam sample registered.sun.xml we should add 4 navigation case to it .username}" required="true" /></td> <td> <h:message for="username"/> </td> </tr> <tr> <td>Real Name</td> <td><h:inputText id="name" value="#{user. */ public interface ActionLocal { public String (). one to .name}" required="true" /></td> . } now we are finished with the action . go to frameworks node and add JSF framework to the project. and select add navigation rule. so I should ask you to take a look at seam reference or wait until next part of this series.jsp in your NetBeans editor change the content to : <%@ taglib uri="http://java. 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 . In web module we just have 2 JSF pages . I should say that it is a very same version of seam sample that is implemented again in NetBeans IDE. register.jsp same as seam sample register.jsp lets code with the register. it will looks like : package sbeans. so extend web module note and under configuration files open the faces-config.xml. used for showing the user that he/she is ed we need to add some navigation case to our faces-config.jsp . a dialog will open . } } } we will need to add same method signature to our session bean local interface .com/jsf/core" prefix="f" %> <%@ taglib prefix="s" uri="http://jboss. From View /register.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.jsp From Outcome success To view registered. so add the method signature to ActionLocal class.jsp . open the register. first of all you need to add JSF framework to web module to do this .sun.jsp registered.

xml and facesconfig.xml and add the following lines to it.sun.jboss. there are some changes that we should make in web.servlet.jndiPattern</param-name> <paramvalue>java:comp/env/registration/#{ejbName}/local</param-value> </context-param> <listener> <listener-class>org.jsp which show that our user is registered.make sure the you add them directly inside <web-app> node.core.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.seam. <h:outputText value="#{user.RegisterActionLocal</local> < ejb-link>RegisterActionBean</ejb-link> </ejb-local-ref> Now open faces-config.}"/> </h:form> </f:view> </body> </html> required="true" No we need to create the registered. <context-param> <description> </description> <param-name>org. open the file in your editor and change its content to looks like : <%@ taglib uri="http://java. you are finished creating your first seam sample in netbeans .com/jsf/core" prefix="f" %> <html> <head> <title>Successfully ed New User</title> </head> <body> <f:view> Welcome. you are successfully ed as <h:outputText value="#{user.jboss.seam.jboss.username}"/>.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.<td> <h:message for="name"/> </td> </tr> <tr> <td>Password</td> <td><h:inputSecret id="password" value="#{user.name}"/>.seam. <lifecycle> <phase-listener>org.init.xml.xml and add the following lines to it. </f:view> </body> </html> Now we are almost finished with JSf files .password}" /></td> <td> <h:message for="password"/> </td> </tr> </s:validateAll> </table> <h:messages globalOnly="true"/> <h:commandButton type="submit" value="" action="#{.sun.jsf.first open web. lets execute the application and see .SeamPhaseListener</phaselistener> </lifecycle> That's it .

I assume you have some experience with Java and understand such concepts as class. HTTP. the JSP engine executes the already-loaded servlet unless the JSP page has changed.0. you'll understand the basic concepts of the JSP and Servlet as web application building components and how they work behind the scenes. In future articles we are going to dig into JSP's and Servlet's advanced features. you see something similar to Figure 1. and Ajax in the context of Java web development. we'll put them together. JSP and Servlet. The tag tag identifies the end of a scriptlet. classpath. You should also have a good understanding of web servers .0. Figure 2: Request/Response Flow when Calling a JSP The next time the page is requested. If you want to create an instance of Date simply by using: Date today = new Date(). After you finish this tutorial. When date. as shown in Figure 2. and helping you prepare your development and deployment environments for the next steps. In the final tutorial. Web Application Part I: Fast Track JSP Development with JSP and XML Date and Time This example contains traditional HTML and some Java code. Figure 1: Requesting date. Scripting ElementsIn the date. will also be revealed.jsp example the full Date class name is used including the package name. the servlet creates a Date object and writes it as a string to the out object.GA/reference/en/html/tutorial. 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. Struts. navigate to http://localhost:8080/RegistrationWebModule/faces/register. It is intended to warm you up by introducing two fundamental Java web components. press f6 and wait until your browser opens . URLs. in which case it is automatically recompiled into a servlet and executed. inheritance.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. For this example. package. Spring Framework. using all of those techniques to build a full-blown production level web application. you will also get full-featured environments for production level web development platforms to take your web programming to the next level.jboss.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 . which may become tedious.jsp . and HTML. etc.jsp) is called. which is an output stream to the browser.jsp is requested from a web browser. Along with this information. which puzzles many new Java web developers and is largely ignored by many tutorials.jsp Behind the ScenesWhen this page (date.com/seam/1. At this point the servlet is handled by the servlet engine just like any other servlet. without having to specify the full class path use the page directive as follows: Sample 2 :date2. experiment with some emerging technologies like XML. it will be compiled (by the JSP engine) into a java servlet. you can find complete explanation of jsp/java codes in Seam tutorial chapter 1 at : http://docs. Hibernate. The relationship between the JSP and Servlet.the result. learn database-driven web development.

where X is the property name. 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. let's see how to modify the process. For example: or . So. In the context of JSP. The request is processed and the result is sent through the response object back to the browser. Also. Figure 4: Form is processed Reusable ComponentsThe above example form is simple in the sense that there is not much code involved. The process.jsp is requested from a web server. Use to declare variables or methods. Example: Using JavaBeans with JSPNow. these are called properties. Protecting your intellectual property by keeping source code secure. platform-independent component model that lets developers write components and reuse them everywhere. or any other type of valid snippet of code. To demonstrate how to handle HTML forms using JSP. the HTML form is defined in a JSP source file. In the above form these are two fields: name and email. Note that the form is created and being handled by code in the same JSP file. These two objects are implicitly available to you.jsp User Info Request Form þÿ Your name: Your email: Process þÿ You have provided the following info: Name: Email: If process. Use the include directive as in to insert the contents of another file in the main JSP file. When more code is involved. Using JSP. you see something similar to Figure 3. For example: . how do you implement the business logic part? That is where JavaBeans come in to play.getParameter method is being used to retrieve data from the form into variables created using JSP tags. JavaBeans contain business logic that returns data to a script on a JSP page. Good components must be able to . Separation of business logic and presentation logic: you can change the way data is displayed without affecting business logic. another way of doing the same thing using the Date and Time Today's date is: As you can see. Sample 4: process. otherwise. A JSP page uses a JavaBean component by setting and getting the properties that it provides. Figure 3: process. For example. and you see something similar to Figure 4. here is an example form with two fields: one for name and the other for email. There are several JSP scripting elements.jsp loaded Enter your name and email and click on Process to submit the form for processing.jsp page prints either a form or the information provided by the user depending on the values of the form's fields. production JSP code should be limited to front end presentation. which in turn formats the data returned from the JavaBean component for display by the browser. Separating business logic from presentation permits changes to either side without affecting the other. If the form's values are null the form is displayed. 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. expressions. Here is an example: . first you write a JavaBean component with setX and getX methods. Here are some conventional rules that will help you use JSP scripting elements effectively: Use to handle declarations. the information provided by the user is displayed. Use to define an expression and cast the result as a String.Date and Time Yet. The request.jsp example above to use JavaBeans. the same thing can be accomplished using different tags and techniques. However. 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. then it is important not to mix business logic with front end presentation in the same file. it can be used to specify import statements. Sample 5 shows a FormBean component. As you can see. Sample 1 above is an example. So. if you have get and set methods: setName and getName then you have a property known as name. In JavaBeans. Use the page directive as in to define the scripting language. This technology is a portable.

to achieve component reuse. } } In order to use the FormBean component in the JSP file. Please click here to give us feedback. and used to initialize the bean's properties. 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.instantiate.com: %0A%0Ahttp%3A%2F%2Fjava. } public void setEmail(String email) { this. and how to create reusable components for handling forms. The next line is executed when the bean is instantiated. and is the author of Distributed Programming with Java (Manning Publications. If you are looking for a solution in which you can separate the two parts. which explains the concepts and benefits of JSP technology. you need to instantiate the bean component.email = email.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.sun. and then shows you how to utilize this exciting technology. import java.name = name. public class FormBean implements Serializable { private String name. In this case. 1999). as shown in Sample 6. It is a great Rapid Application Development (RAD) approach to Web applications. A Sun Developer Network SiteUnless otherwise licensed. private String email. namely JSP and XML. JavaServer Pages (JSP) are here. Sample 5: FormBean. This series of articles provides a hands-on tutorial explaining how to develop modern Web applications for today's and tomorrow's market. because JSP pages have XML support built right into them in the form of JSP custom tag libraries. } public String getEmail() { return email. Your bean class must support persistence by implementing the interface Serializable or Externalizable. JSP and XML make an excellent combination for web applications that share information. This series begins with this article. } public String getName() { return name. both properties (name and email) are set using a single statement. code in all technical manuals herein (including articles. look no further.io.Comments?About Sun | About This Site Newsletters | Contact Us | EmploymentHow to Buy | Licensing | Terms of Use | Privacy | Trademarks Copyright 1994-2009 Sun Microsystems. 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. it is possible to set the properties one at a time. samples) is provided under this License. Alternatively. FAQs. This is done using the tag.java package userinfo. JSP pages allow you to separate front-end presentation from business logic (middle and back-end tiers). Here is an example of how you would set the name property: Once the properties have been initialized with data retrieved from the form.interoperate with other components from different vendors. Stay tuned for more information on this in the next article in this series. XML Sun Developer RSS Feeds&body=Check out this page on sun. Inc. public FormBean() { name = null. The next article will discuss the capabilities that the JSP technology provides that are ideally suited for working with XML. property values are retrieved for presentation using in the else part.*. Therefore. 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. Mahmoud provides Java consulting and training services. and show you how to effectively use JSP with XML. } public void setName(String name) { this. . coffeecup For more informationJSP Tomcat Comparing JSP and ASP About the AuthorQusay H. email = null. but first you need to retrieve the form's date. Qusay has published dozens of articles on Java.

• Extensible Tags: JSP pages have an advanced feature known as extensible tags.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. JSP pages are compiled into Java servlets and loaded into memory the first time they are called. web browsers. and so on) already support JSP technology. session tracking. and database connection. ASP pages work only with Microsoft IIS and Personal Web Server. • JSP pages use JavaBeans technology as the component architecture and ASP pages use ActiveX components. however. . The problem with either CGI or servlets. JSP pages are platform-independent and ASP pages are not. The increasingly sophisticated applications to enable this marketplace require a technology for presenting dynamic information. compile. This mechanism enables developers to create custom tags. By contrast. and a key component of the Java 2 Enterprise Edition (J2EE) specification. JSP pages are a third generation solution that can be combined easily with some second generation solutions. The problem is that their solutions were specific to their server products. You cannot do this with ASP pages. freely available specification developed by Sun Microsystems as an alternative to Microsoft's Active Server Pages (ASP) technology. Many of the commercially available application servers (such as BEA WebLogic. First generation solutions included CGI. while JSP pages do not tie you to any specific web server or operating system. This gives JSP pages aspeed and scalability advantage over ASP pages. Therefore. and deploy life cycle. JSP pages are becoming a widely supported standard. Second generation solutions included web server vendors providing plug-ins and APIs for their servers. Some of the trivial differences are: • ASP pages are written in VBScript and JSP pages are written in the Java programming language. and making it easier and faster to build web-based applications that work with a variety of other technologies: web servers. their solution only worked with Microsoft IIS or Personal Web Server. Using ASP pages requires a commitment to Microsoft products. Therefore. Microsoft provided Active Server Pages (ASP) that made it easier to create dynamic content. 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. In other words. Live JRun. JSP versus ASP JSP and ASP deliver similar functionality. creating dynamic content. Beyond these trivial differences. The problem with CGI scripts is scalability. application servers and other development tools. a new process is created for every request. 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. they are always interpreted. • Freedom of Choice: Unless you install Chili!Soft ASP. and executed for all subsequent calls. They both use tags to allow embedded code in an HTML page. JavaServer Pages (JSP) The JSP technology is an open. which is a mechanism for running external programs through a web server. is that you have to follow the write. IBM WebSphere. However. extensible tags allow you to extend the JSP pages tag syntax. For example. Orion. Servlets make it easier to write server-side applications using Java technology.

you may get an Out of space environment error when you try to start Tomcat.sh for UNIX.htm". • Save your . 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. Software Environment To run JSP pages. you need a web server with a web container that conforms to JSP and servlet specifications. use TOMCAT_HOME/bin/startup.Date().2 and JSP 1.jsp files in TOMCAT_HOME/webapps/examples/jsp and your JavaBeans classes in TOMCAT_HOME/webapps/examples/web-inf/classes. The file extension of a JSP page is ". The web container executes on the web server and manages the execution of all JSP pages and servlets running on that web server.2.html" or ".jsp is requested from a web browser. By default.jsp" rather than ". Tomcat 3.util. • To start Tomcat.println("Today's date is: "+today). see Comparing JSP and ASP.jsp <HTML> <HEAD> <TITLE>JSP Example</TITLE> </HEAD> <BODY BGCOLOR="ffffcc"> <CENTER> <H2>Date and Time</H2> <% java. Note: If you work under Windows. Download and install binary versions of Tomcat.For a more detailed comparison between JSP pages and ASP pages.sys file and add the following line: SHELL=c:\PATHTO\command.Date today = new java. Here is a simple example: Sample 1: date.bat for windows or startup. it will start listening on port 8080. %> </CENTER> </BODY> </HTML> This example contains traditional HTML and some Java code. you see . out. When date.1 specifications. and the %> tag identifies the end of a scriptlet. The tag <% identifies the beginning of a scriptlet.1 is a complete reference implementation for the Java Servlet 2.com /E:4096 /P. How JSP Pages Work A JSP page is basically a web page with traditional HTML and bits of Java code.util. • Set the TOMCAT_HOME environment variable to point to the root directory of your Tomcat installation. and that tells the server that this page requires special handling that will be accomplished by a server extension or a plug-in. To configure Tomcat: • Set the environment variable JAVA_HOME to point to the root directory of your Java 2 Standard Edition (J2SE) installation.

*" %> <HTML> <HEAD> <TITLE>JSP Example</TITLE> </HEAD> .jsp example the full Date class name is used including the package name. 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.jsp Behind the Scenes When this page (date. Scripting Elements In the date.jsp <%@page import="java. which may become tedious. which is an output stream to the browser.something similar to Figure 1. At this point the servlet is handled by the servlet engine just like any other servlet. Figure 1: Requesting date. If you want to create an instance of Date simply by using: Date today = new Date(). in which case it is automatically recompiled into a servlet and executed. For this example. the JSP engine executes the already-loaded servlet unless the JSP page has changed. the servlet creates a Date object and writes it as a string to the out object. as shown in Figure 2.jsp) is called. it will be compiled (by the JSP engine) into a java servlet. Figure 2: Request/Response Flow when Calling a JSP The next time the page is requested. without having to specify the full class path use the page directive as follows: Sample 2 :date2.util.

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. out. it can be used to specify import statements. %> to define an expression and cast the result as a String.Date today = new java. %> </CENTER> </BODY> </HTML> Yet.html" %>..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.Date() %>. For example: <%! int x = 10..util. the same thing can be accomplished using different tags and techniques. • Use the include directive as in <%@ include .<BODY BGCOLOR="ffffcc"> <CENTER> <H2>Date and Time</H2> <% java. Also.. For example: <%= a+b %> or <%= new java. Here is an example: <%@page language="java" import="java. %> to define the scripting language. expressions.. double y = 2.jsp <%@page import="java. another way of doing the same thing using the <%= tag is by writing: Sample 3:date3.. Using JSP. %> to handle declarations.. Sample 1 above is an example.util.println("Today's date is: "+today). %>.util... • Use <%= . The request is processed and the .. There are several JSP scripting elements.Date()..0. %> to declare variables or methods. For example: <%@include file="copyright..util.*" %>. • Use <%! . • Use the page directive as in <%@page . 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. %> to insert the contents of another file in the main JSP file. Here are some conventional rules that will help you use JSP scripting elements effectively: • Use <% . or any other type of valid snippet of code.

%> <% name = request. the information provided by the user is displayed.getParameter("name"). email.jsp <HTML> <HEAD> <TITLE>Form Example</TITLE> </HEAD> <BODY BGCOLOR="#ffffcc"> <% if (request. you see something similar to Figure 3.getParameter method is being used to retrieve data from the form into variables created using JSP tags. The process. As you can see. %> <P> <B>You have provided the following info</B>: <P> <B>Name</B>: <%= name %><P> <B>Email</B>: <%= email %> <% } %> </BODY> </HTML> If process.getParameter("email").getParameter("name")== null && request.result is sent through the response object back to the browser. To demonstrate how to handle HTML forms using JSP.jsp page prints either a form or the information provided by the user depending on the values of the form's fields.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. the HTML form is defined in a JSP source file. These two objects are implicitly available to you. here is an example form with two fields: one for name and the other for email. Note that the form is created and being handled by code in the same JSP file.getParameter("email") == null) { %> <CENTER> <H2>User Info Request Form</H2> <FORM METHOD="GET" ACTION="/developer/technicalArticles/xml/WebAppDev/process. The request. email = request. Sample 4: process. If the form's values are null the form is displayed.jsp is requested from a web server. . otherwise.

and you see something similar to Figure 4. In the above form these are two fields: name and email. if you have get and set methods: setName and getName then you have a property known as name.Figure 3: process. For example. how do you implement the business logic part? That is where JavaBeans come in to play.jsp example above to use JavaBeans. Separation of business logic and presentation logic: you can change the way data is displayed without affecting business logic. Figure 4: Form is processed Reusable Components The above example form is simple in the sense that there is not much code involved. Example: Using JavaBeans with JSP Now. So. This technology is a portable. where X is the property name. these are called properties. Separating business logic from presentation permits changes to either side without affecting the other. JavaBeans contain business logic that returns data to a script on a JSP page. platform-independent component model that lets developers write components and reuse them everywhere. let's see how to modify the process. So. Therefore. which in turn formats the data returned from the JavaBean component for display by the browser. Sample 5 shows a FormBean component. production JSP code should be limited to front end presentation. However. When more code is involved. • Protecting your intellectual property by keeping source code secure. first you write a JavaBean component with setX and getX methods. to . Good components must be able to interoperate with other components from different vendors. A JSP page uses a JavaBean component by setting and getting the properties that it provides. In the context of JSP. then it is important not to mix business logic with front end presentation in the same file. 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. In JavaBeans.jsp loaded Enter your name and email and click on Process to submit the form for processing.

} } In order to use the FormBean component in the JSP file. Sample 5: FormBean. youremail. In this case.io. there are two important rules (which are imposed by the JavaBeans architecture) to follow: 1. import java. email = null.java package userinfo.*.achieve component reuse. public class FormBean implements Serializable { private String name. } public void setName(String name) { this. private String email.name = name. both properties (name and email) are set using a single statement.email = email. %> <jsp:setProperty name= "formbean" property="name" value="<%=yourname%>"/> Once the properties have been initialized with data retrieved from the form. } public void setEmail(String email) { this. } public String getName() { return name. The next line <jsp:setProperty> is executed when the bean is instantiated. it is possible to set the properties one at a time. Your bean class must support persistence by implementing the interface Serializable or Externalizable. } public String getEmail() { return email. This is done using the <jsp:useBean> tag. Here is an example of how you would set the name property: <%! String yourname.instantiate. public FormBean() { name = null. Alternatively. and used to initialize the bean's properties. but first you need to retrieve the form's date. property values are retrieved for .getParameter("name"). 2. Your bean class must provide a constructor with no arguments so it can be created using Beans. %> <% yourname = request. you need to instantiate the bean component.

namely JSP and XML. Sample 6: process2. JSP and XML make an excellent combination for web applications that share information.getParameter("name")==null && request. as shown in Sample 6. The next article will discuss the capabilities that the JSP technology provides that are ideally suited for working with XML.jsp <jsp:useBean id="formbean" class= "userinfo. Stay tuned for more information on this in the next article in this series. because JSP pages have XML support built right into them in the form of JSP custom tag libraries.FormBean"/> <jsp:setProperty name="formbean" property= "*"/> <HTML> <HEAD> <TITLE>Form Example</TITLE> </HEAD> <BODY BGCOLOR="#ffffcc"> <% if (request.getParameter("email") == null) { %> <CENTER> <H2>User Info Request Form </H2> <form method="GET" action="/developer/technicalArticles/xml/WebAppDev/process2. and show you how to effectively use JSP with XML.presentation using <jsp:getProperty> in the else part.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. .

NET.Automatically generate code for N-Tier VB applications and components.Data-aware Input Controls for .NET database applications.XML tool which provides conversion utilities for migration of traditional HTML Web sites to advanced XML-based sites.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 .NET . Cold Fusion .Different web appilication tools Web Application Development ASPxGrid . ComponentOne Input for .NET ComponentOne Studio Enterprise includes the complete line of . ASP.Automatically generate code for N-Tier VB applications and components.NET AireLogic publishes automatically generated client-and server-side code to any designated application server Altova stylevision Professional .Net .Web application server ComponentOne DataObjects for .NET.Comprehensive framework for creating .NET). COM Express Suite (ActiveX and .NET . Mobile Device. and ActiveX products DataDiplomat Level One .100% Native Components for ASP. COM Express for .

NET framework.Create desktop like toolbars in browser PinEdit .D.InaEmailSend . and open development tools Macromedia Web Learning Studio a Getting Started with Online Learning guide.Extensions and Enhancements for Swing JClass HiGrid .Creating Professional Tables and Forms JClass PageLayout .Ideal Interface JClass JarMaster .A. controls suite .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. powerful.A.A.NET components for rapid web-development and content management.NET IDE .Add a WYSIWYG HTML editor to your browser based solutions or applications.A component that can send mail via an SMTP Server. R. and learning extensions. Macromedia Studio MX .NET IDE in a small package ProtoFax .Package and Manage Java Classes JClass LiveTable .integrated suite of easy-to-use. JBuilder is the perfect tool for creating pure Java business and database applications JClass Chart with Gold Support .Deliver faxes and alphanumeric pages from the Internet R. R.D.Ground-breaking Windows development environment PINSuite .Powerful .component for building collapsible side-menu systems. . PrimalCode .panelbar . designer .Professional Printing Power in Java JClass ServerViews .D.Professional Graphs and Charts JClass DesktopViews .is a comprehensive collection of client-side Java components JClass Elements .a collection of indispensable ASP.Collection of ambitious components for web development PINToolbar . Net Express .browser-based componentware CMS tool for the .

WebInput.is the platform of choice for deploying e-business and distributed applications Simplicity for Java designs great Java applets and applications Sitespring Server .Powerful input control for your ASP.NET .NET Server Express . 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 .Add advanced combo box drop down lists to your ASP.Make your team more productive and profitable SoftArtisans XFile is a complete HTTP client Sybase Enterprise Application Server & Studio -.treeview .NET applications.R.A.helps you build scalable Web applications Visual DataFlex helps you create high-performance database applications WebCombo.NET applications WebLogic Workshop .Build service-oriented.treeview component for ASP.NET .D.

Sign up to vote on this title
UsefulNot useful