Monday, December 9, 2013

JSP - Enhance the first JSP example with Java Beans

In the previous article, we saw a first example of using JSP, where Java was embedded into the HTML to perform the dynamic part.
In this article, we are going to enhance the structure of the previous example, by making use of a Java Bean.
This structure enhances readability, and separates the code of the user interface from the code to perform computations.

In the case of more complex applications, the structure of the first example would lead to a solution difficult to understand and maintain. The structure of the solution presented in this article is more flexible, readable and so more easy to maintain and evolve.

So, we shall create a Net Beans project, just like in the first example, and make the same modifications to index.jsp. Then, we create the new JSP file (newjsp.jsp):


Contrary to what we saw in the First JSP Example, this file has not embedded the code to obtain the parameters or the calculation of the operation result. It has, instead, a JavaBean component that is no more than a class who are passed the parameters and performs the required calculations.

First JSP example

Java Server Pages (JSP) is a Java technology that allows creating web pages with a mix of static HTML and dynamic HTML. The dynamic part is generated by using Java language scripts that are embbeded in the HTML code through special Tags, recognized by the application server.

In this article we will see a small example that will serve to introduce some of the JSP tags and help in understanding how does Java work in the middle of all the rest.

The example is made with NetBeans IDE 7.2.1, and it consists of a small calculator that will allow to perform the four arithmetic operations on two integer operands.

Let's start by creating a new project in NetBeans, of type Web Application:


As applicational server we will use GlassFish:

 (we don't select any framework, in step 4 of creating a new project)

NetBeans creates a project structure with a file index.jsp, which will generate the initial page of the project:



Initial contents of file index.jsp: