Thursday, October 2, 2008

JSP Actions

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include:
  • jsp:include - Include a file at the time the page is requested. See Section 8.1.
  • jsp:useBean - Find or instantiate a JavaBean. See Section 8.2 for an overview, and Section 8.3 for details.
  • jsp:setProperty - Set the property of a JavaBean. See Section 8.4.
  • jsp:getProperty - Insert the property of a JavaBean into the output. See Section 8.5.
  • jsp:forward - Forward the requester to a new page. See Section 8.6.
  • jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. See Section 8.7.
These actions are described in more detail below. Remember that, as with XML in general, the element and attribute names are case sensitive.

8.1 The jsp:include Action

This action lets you insert files into the page being generated. The syntax looks like this:


Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and precludes the included page from containing general JSP code (it cannot set HTTP headers, for example), but it gains significantly in flexibility. For example, here is a JSP page that inserts four different snippets into a "What's New?" Web page. Each time the headlines change, authors only need to update the four files, but can leave the main JSP page unchanged.

WhatsNew.jsp

You can also download the source or try it on-line.




What's New
HREF="My-Style-Sheet.css"
TYPE="text/css">


VLINK="#551A8B" ALINK="#FF0000">




What's New at JspNews.com




Here is a summary of our four most recent news stories:









Here's a typical result:
WhatsNew Output

8.2 The jsp:useBean Action

This action lets you load in a JavaBean to be used in the JSP page. This is a a very useful capability because it lets you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over servlets alone. The simplest syntax for specifying that a bean should be used is:
name" class="package.class" />

This usually means "instantiate an object of the class specified by class, and bind it to a variable with the name specified by id." However, as we'll see shortly, you can specify a scope attribute that makes the bean associated with more than just the current page. In that case, it is useful to obtain references to existing beans, and the jsp:useBean action specifies that a new object is instantiated only if there is no existing one with the same id and scope. Now, once you have a bean, you can modify its properties via jsp:setProperty, or by using a scriptlet and calling a method explicitly on the object with the variable name specified earlier via the id attribute. Recall that with beans, when you say "this bean has a property of typeX called foo", you really mean "this class has a method called getFoo that returns something of type X, and another method called setFoo that takes an X as an argument." The jsp:setProperty action is discussed in more detail in the next section, but for now note that you can either supply an explicit value, give a param attribute to say that the value is derived from the named request parameter, or just list the property to indicate that the value should be derived from the request parameter with the same name as the property. You read existing properties in a JSP expression or scriptlet by calling the appropriate getXxx method, or more commonly, by using the jsp:getProperty action.

Note that the class specified for the bean must be in the server's regular class path, not the part reserved for classes that get automatically reloaded when they change. For example, in the Java Web Server, it and all the classes it uses should go in the classes directory or be in a jar file in the lib directory, not be in the servlets directory.

Here is a very simple example that loads a bean and sets/gets a simple String parameter.

BeanTest.jsp

You can also download the source or try it on-line.




Reusing JavaBeans in JSP
HREF="My-Style-Sheet.css"
TYPE="text/css">







Reusing JavaBeans in JSP





property="message"
value="Hello WWW" />


Message:





SimpleBean.java

Here's the source code for the bean used in the BeanTest JSP page. You can also download the source.
package hall;


public class SimpleBean {
private String message = "No message specified";

public String getMessage() {
return(message);
}

public void setMessage(String message) {
this.message = message;
}
}
Here's a typical result:
BeanTest Output

8.3 More jsp:useBean Details

The simplest way to use a bean is to use
name" class="package.class" />
to load the bean, then use jsp:setProperty and jsp:getProperty to modify and retrieve bean properties. However, there are two other options. First, you can use the container format, namely

Body

to indicate that the Body portion should be executed only when the bean is first instantiated, not when an existing bean is found and used. As discussed below, beans can be shared, so not all jsp:useBean statements result in a new bean being instantiated. Second, in addition to id and class, there are three other attributes that you can use: scope, type, and beanName. These attributes are summarized in the following table.

Atribute Usage
id Gives a name to the variable that will reference the bean. A previous bean object is used instead of instantiating a new one if one can be found with the same id and scope.
class Designates the full package name of the bean.
scope Indicates the context in which the bean should be made available. There are four possible values: page, request, session, and application. The default, page, indicates that the bean is only available on the current page (stored in the PageContext of the current page). A value of request indicates that the bean is only available for the current client request (stored in the ServletRequest object). A value of session indicates that the object is available to all pages during the life of the current HttpSession. Finally, a value of application indicates that it is available to all pages that share the same ServletContext. The reason that the scope matters is that a jsp:useBean entry will only result in a new object being instantiated if there is no previous object with the same id and scope. Otherwise the previously existing object is used, and any jsp:setParameter elements or other entries between the jsp:useBean start and end tags will be ignored.
type Specifies the type of the variable that will refer to the object. This must match the classname or be a superclass or an interface that the class implements. Remember that the name of the variable is designated via the id attribute.
beanName Gives the name of the bean, as you would supply it to the instantiate method of Beans. It is permissible to supply a type and a beanName, and omit the class attribute.

8.4 The jsp:setProperty Action

You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:


...
property="someProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:


...
property="someProperty" ... />

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

There are four possible attributes of jsp:setProperty:

Attribute Usage
name This required attribute designates the bean whose property will be set. The jsp:useBean element must appear before the jsp:setProperty element.
property This required attribute indicates the property you want to set. However, there is one special case: a value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
value This optional attribute specifies the value for the property. String values are automatically converted to numbers, boolean, Boolean, byte, Byte, char, and Character via the standard valueOf method in the target or wrapper class. For example, a value of "true" for a boolean or Boolean property will be converted via Boolean.valueOf, and a value of "42" for an int or Integer property will be converted via Integer.valueOf. You can't use both value and param, but it is permissible to use neither. See the discussion of param below.
param This optional attribute designates the request parameter from which the property should be derived. If the current request has no such parameter, nothing is done: the system does not pass null to the setter method of the property. Thus, you can let the bean itself supply default values, overriding them only when the request parameters say to do so. For example, the following snippet says "set the numberOfItems property to whatever the value of the numItems request parameter is, if there is such a request parameter. Otherwise don't do anything."
                property="numberOfItems"

param="numItems" />
If you omit both value and param, it is the same as if you supplied a param name that matches the property name. You can take this idea of automatically using the request property whose name matches the property one step further by supplying a property name of "*" and omitting both value and param. In this case, the server iterates through available properties and request parameters, matching up ones with identical names.
Here's an example that uses a bean to create a table of prime numbers. If there is a parameter named numDigits in the request data, it is passed into the bean's numDigits property. Likewise for numPrimes.

JspPrimes.jsp

To download the JSP source, right click on the source code link. You can also download the source code for the NumberedPrimes bean referenced by the jsp:useBean element. Browse the source code directory for other Java classes used by NumberedPrimes. The best way to try it out on-line is to start with the HTML page that acts as a front end to it.




Reusing JavaBeans in JSP
HREF="My-Style-Sheet.css"
TYPE="text/css">







Reusing JavaBeans in JSP








Some
digit primes:




Here's a typical result:
JspPrimes Output

8.5 The jsp:getProperty Action

This element retrieves the value of a bean property, converts it to a string, and inserts it into the output. The two required attributes are name, the name of a bean previously referenced via jsp:useBean, and property, the property whose value should be inserted. Here's an example; for more examples, see Sections 8.2 and 8.4.


...

  • Number of items:

  • Cost of each:


8.6 The jsp:forward Action

This action lets you forward the request to another page. It has a single attribute, page, which should consist of a relative URL. This could be a static value, or could be computed at request time, as in the two examples below.


" />

8.7 The jsp:plugin Action

This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

9. Comments and Character Quoting Conventions

There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%>
A JSP comment. Ignored by JSP-to-scriptlet translator. Any embedded JSP scripting elements, directives, or actions are ignored.
An HTML comment. Passed through to resultant HTML. Any embedded JSP scripting elements, directives, or actions are executed normally.
<\%
Used in template text (static HTML) where you really want "<%".
%\>
Used in scripting elements where you really want "%>".
\'
A single quote in an attribute that uses single quotes. Remember, however, that you can use either single or double quotes, and the other type of quote will then be a regular character.
\"
A double quote in an attribute that uses double quotes. Remember, however, that you can use either single or double quotes, and the other type of quote will then be a regular character.
%\>
%> in an attribute.
<\%
<% in an attribute.

Predefined Variables

To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below.
7.1 request
This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice.
7.2 response
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
7.3 out
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
7.4 session
This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
7.5 application
This is the ServletContext as obtained via getServletConfig().getContext().
7.6 config
This is the ServletConfig object for this page.
7.7 pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.
7.8 page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.
8. Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include:

* jsp:include - Include a file at the time the page is requested. See Section 8.1.
* jsp:useBean - Find or instantiate a JavaBean. See Section 8.2 for an overview, and Section 8.3 for details.
* jsp:setProperty - Set the property of a JavaBean. See Section 8.4.
* jsp:getProperty - Insert the property of a JavaBean into the output. See Section 8.5.
* jsp:forward - Forward the requester to a new page. See Section 8.6.
* jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. See Section 8.7.

These actions are described in more detail below. Remember that, as with XML in general, the element and attribute names are case sensitive.
8.1 The jsp:include Action
This action lets you insert files into the page being generated. The syntax looks like this:



Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and precludes the included page from containing general JSP code (it cannot set HTTP headers, for example), but it gains significantly in flexibility. For example, here is a JSP page that inserts four different snippets into a "What's New?" Web page. Each time the headlines change, authors only need to update the four files, but can leave the main JSP page unchanged.
WhatsNew.jsp
You can also download the source or try it on-line.




What's New








What's New at JspNews.com




Here is a summary of our four most recent news stories:










Here's a typical result:
WhatsNew Output
8.2 The jsp:useBean Action
This action lets you load in a JavaBean to be used in the JSP page. This is a a very useful capability because it lets you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over servlets alone. The simplest syntax for specifying that a bean should be used is:



This usually means "instantiate an object of the class specified by class, and bind it to a variable with the name specified by id." However, as we'll see shortly, you can specify a scope attribute that makes the bean associated with more than just the current page. In that case, it is useful to obtain references to existing beans, and the jsp:useBean action specifies that a new object is instantiated only if there is no existing one with the same id and scope. Now, once you have a bean, you can modify its properties via jsp:setProperty, or by using a scriptlet and calling a method explicitly on the object with the variable name specified earlier via the id attribute. Recall that with beans, when you say "this bean has a property of typeX called foo", you really mean "this class has a method called getFoo that returns something of type X, and another method called setFoo that takes an X as an argument." The jsp:setProperty action is discussed in more detail in the next section, but for now note that you can either supply an explicit value, give a param attribute to say that the value is derived from the named request parameter, or just list the property to indicate that the value should be derived from the request parameter with the same name as the property. You read existing properties in a JSP expression or scriptlet by calling the appropriate getXxx method, or more commonly, by using the jsp:getProperty action.

Note that the class specified for the bean must be in the server's regular class path, not the part reserved for classes that get automatically reloaded when they change. For example, in the Java Web Server, it and all the classes it uses should go in the classes directory or be in a jar file in the lib directory, not be in the servlets directory.

Here is a very simple example that loads a bean and sets/gets a simple String parameter.
BeanTest.jsp
You can also download the source or try it on-line.




Reusing JavaBeans in JSP








Reusing JavaBeans in JSP







Message:






SimpleBean.java
Here's the source code for the bean used in the BeanTest JSP page. You can also download the source.

package hall;

public class SimpleBean {
private String message = "No message specified";

public String getMessage() {
return(message);
}

public void setMessage(String message) {
this.message = message;
}
}

Here's a typical result:
BeanTest Output
8.3 More jsp:useBean Details
The simplest way to use a bean is to use

to load the bean, then use jsp:setProperty and jsp:getProperty to modify and retrieve bean properties. However, there are two other options. First, you can use the container format, namely

Body

to indicate that the Body portion should be executed only when the bean is first instantiated, not when an existing bean is found and used. As discussed below, beans can be shared, so not all jsp:useBean statements result in a new bean being instantiated. Second, in addition to id and class, there are three other attributes that you can use: scope, type, and beanName. These attributes are summarized in the following table.

Atribute Usage
id Gives a name to the variable that will reference the bean. A previous bean object is used instead of instantiating a new one if one can be found with the same id and scope.
class Designates the full package name of the bean.
scope Indicates the context in which the bean should be made available. There are four possible values: page, request, session, and application. The default, page, indicates that the bean is only available on the current page (stored in the PageContext of the current page). A value of request indicates that the bean is only available for the current client request (stored in the ServletRequest object). A value of session indicates that the object is available to all pages during the life of the current HttpSession. Finally, a value of application indicates that it is available to all pages that share the same ServletContext. The reason that the scope matters is that a jsp:useBean entry will only result in a new object being instantiated if there is no previous object with the same id and scope. Otherwise the previously existing object is used, and any jsp:setParameter elements or other entries between the jsp:useBean start and end tags will be ignored.
type Specifies the type of the variable that will refer to the object. This must match the classname or be a superclass or an interface that the class implements. Remember that the name of the variable is designated via the id attribute.
beanName Gives the name of the bean, as you would supply it to the instantiate method of Beans. It is permissible to supply a type and a beanName, and omit the class attribute.
8.4 The jsp:setProperty Action
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:


...


In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:


...



Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

There are four possible attributes of jsp:setProperty:

Attribute Usage
name This required attribute designates the bean whose property will be set. The jsp:useBean element must appear before the jsp:setProperty element.
property This required attribute indicates the property you want to set. However, there is one special case: a value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
value This optional attribute specifies the value for the property. String values are automatically converted to numbers, boolean, Boolean, byte, Byte, char, and Character via the standard valueOf method in the target or wrapper class. For example, a value of "true" for a boolean or Boolean property will be converted via Boolean.valueOf, and a value of "42" for an int or Integer property will be converted via Integer.valueOf. You can't use both value and param, but it is permissible to use neither. See the discussion of param below.
param This optional attribute designates the request parameter from which the property should be derived. If the current request has no such parameter, nothing is done: the system does not pass null to the setter method of the property. Thus, you can let the bean itself supply default values, overriding them only when the request parameters say to do so. For example, the following snippet says "set the numberOfItems property to whatever the value of the numItems request parameter is, if there is such a request parameter. Otherwise don't do anything."



If you omit both value and param, it is the same as if you supplied a param name that matches the property name. You can take this idea of automatically using the request property whose name matches the property one step further by supplying a property name of "*" and omitting both value and param. In this case, the server iterates through available properties and request parameters, matching up ones with identical names.
Here's an example that uses a bean to create a table of prime numbers. If there is a parameter named numDigits in the request data, it is passed into the bean's numDigits property. Likewise for numPrimes.
JspPrimes.jsp
To download the JSP source, right click on the source code link. You can also download the source code for the NumberedPrimes bean referenced by the jsp:useBean element. Browse the source code directory for other Java classes used by NumberedPrimes. The best way to try it out on-line is to start with the HTML page that acts as a front end to it.




Reusing JavaBeans in JSP








Reusing JavaBeans in JSP








Some
digit primes:





Here's a typical result:
JspPrimes Output
8.5 The jsp:getProperty Action
This element retrieves the value of a bean property, converts it to a string, and inserts it into the output. The two required attributes are name, the name of a bean previously referenced via jsp:useBean, and property, the property whose value should be inserted. Here's an example; for more examples, see Sections 8.2 and 8.4.


...


  • Number of items:

  • Cost of each:



8.6 The jsp:forward Action
This action lets you forward the request to another page. It has a single attribute, page, which should consist of a relative URL. This could be a static value, or could be computed at request time, as in the two examples below.


">

8.7 The jsp:plugin Action
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.
9. Comments and Character Quoting Conventions
There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose

<%-- comment --%>

A JSP comment. Ignored by JSP-to-scriptlet translator. Any embedded JSP scripting elements, directives, or actions are ignored.



An HTML comment. Passed through to resultant HTML. Any embedded JSP scripting elements, directives, or actions are executed normally.

<\% Used in template text (static HTML) where you really want "<%". %\>

Used in scripting elements where you really want "%>".

\'

A single quote in an attribute that uses single quotes. Remember, however, that you can use either single or double quotes, and the other type of quote will then be a regular character.

\"

A double quote in an attribute that uses double quotes. Remember, however, that you can use either single or double quotes, and the other type of quote will then be a regular character.

%\>

%> in an attribute.

<\%

<% in an attribute.

Protecting your website with a login page

Some sites require that all users log-in using a username and password, before being able to visit any page.

This can be done using JSP sessions or servlets, and in fact this was a common technique for a while. But starting with a new release of Servlets specifications (2.2) from Sun, this feature is now very simple to implement.

It is no longer necessary to use JSP techniques to provide login/password protection, but it is still a very common requirement of web-sites, therefore a brief overview is provided here.

To password-protect your site, you just need to design a login page. This page can be as simple or complicated as you need it to be. It must contain a

tag, with the METHOD set to POST and the ACTION set to "j_security_check".

The target j_security_check is provided by the application server, and does not need to be coded.

The form must contain two fields, named j_username and j_password respectively for the username and password. Typically, the username field will be a TEXT input field, and the password field will be a PASSWORD input field.

After this, you must tell your application server to password protect your pages using the login page you have provided. The details will vary from server to server, but a good implementation will provide you hooks that you can use, for example, to match usernames and passwords against a database. (E.g., in Blazix you can supply an implementation of the interface desisoft.deploy.AuthCheck to check usernames and passwords against a database or other sources.)

Tag libraries

JSP 1.1 introduces a method of extending JSP tags, called "tag libraries". These libraries allow addition of tags similar to jsp:include or jsp:forward, but with different prefixes other than jsp: and with additional features.

To introduce you to tag libraries, in this tutorial we use the Blazix tag library as an example. This tag library comes bundled with the Blazix server. If you are not using the Blazix Server, you may just want to review the material to get familiar with the syntax, and continue on to the next page.

Each tag-library will have its own tag-library specific documentation. In order to use the tag library, you use the "taglib" directive to specify where your tag library's "description" resides. For the Blazix tag library, the (recommended) directive is as follows

<%@ taglib prefix="blx" uri="/blx.tld" %>
The "uri" specifies where to find the tag library description. The "prefix" is unique for the tag library. This directive is saying that we will be using the tags in this library by starting them with blx:

The Blazix tag library provides a blx:getProperty tag. This tag can be used to allow the user to edit form data. In our GetName.jsp file, we will now add a jsp:useBean and place the form inside blx:getProperty.

The new GetName.jsp is

<%@ taglib prefix="blx" uri="/blx.tld" %>






What's your name?

What's your e-mail address?

What's your age?





Note that the blx:getProperty doesn't end with /> but is instead terminated by a separate line. This puts all the form input fields inside the blx:getProperty so they can be appropriately modified by the tag library.

Try putting a link to GetName.jsp from the NextPage.jsp, and you will see that the bean's data shows up automatically in the input fields.

The user can now edit the data.

We still have a couple of problems. The user cannot clear out the name field. Moreover, if the user enters a bad item in the "age" field, something which is not a valid integer, a Java exception occurs.

We will use another tag from the Blazix tag library to take care of this. Blazix offers a blx:setProperty tag that can be used to take care of these problems. blx:setProperty allows us to define an exception handler method. If an exception occurs, we can collect an error message for the user and continue processing.

Following is a version of SaveName.jsp that processes any errors, and either shows the user GetName.jsp again to user can enter the data correctly, or automatically forwards to NextPage.jsp.

<%@ taglib prefix="blx" uri="/blx.tld" %>

<%!
boolean haveError;
StringBuffer errors;

public void errorHandler( String field,
String value,
Exception ex )
{
haveError = true;
if ( errors == null )
errors = new StringBuffer();
else
errors.append( "

" );
errors.append( "

Value for field \"" +
field + "\" is invalid." );
if ( ex instanceof java.lang.NumberFormatException )
errors.append( " The value must be a number." );
}
%>
<%
// Variables must be initialized outside declaration!
haveError = false;
errors = null;
%>



property="*"
onError="errorHandler"/>
<%
if ( haveError ) {
out.println( errors.toString());
pageContext.include( "GetName.jsp" );
} else
pageContext.forward( "NextPage.jsp" );
%>

Note that haveError and errors must be re-initialized each time, therefore they are being initialized outside of the declaration.

[Also notice the use of pageContext.include and pageContext.forward. These are like jsp:include and jsp:forward, but are more convenient to use from within Java blocks. pageContext is another pre-defined variable that makes it easy to do certain operations from within Java blocks.]

Here, if an error occurs during the processing of blx:setProperty, we display the error and then include the GetName.jsp again so user can correct the error. If no errors occur, we automatically forward the user to NextPage.jsp.

There is still a problem with the forms, the "age" shows up as zero initially rather than being empty. This can be fixed by adding "emptyInt=0" to both the blx:getProperty and blx:setProperty tags (bean fields should be initialized to 0.) It happens that "0" is not a valid value for age, so we can use "0" to mark empty strings. If "0" were a valid value for age, we could have added "emptyInt=-1" (and made sure to initialize the bean fields to -1.)

Another small problem is that the "" tag gets doubled if there is an error and we end up including "GetName.jsp". A more elegant solution is to remove the out.println, and pass back the error as shown

<%

if ( haveError ) {
request.setAttribute( "errors",
errors.toString());
pageContext.forward( "GetName.jsp" );
} else
pageContext.forward( "NextPage.jsp" );
%>
We can then do a "request.getAttribute" in the GetName.jsp, and if the returned value is non-null, display the error.

Beans and Form processing

Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy.

The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields. For instance, let us modify our GetName.html to also collect email address and age.

The new version of GetName.html is




What's your name?

What's your e-mail address?

What's your age?






To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is upper-cased. So if the field is "email", its "setter" method will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public.


package user;

public class UserData {

String username;
String email;
int age;

public void setUsername( String value )
{
username = value;
}

public void setEmail( String value )
{
email = value;
}

public void setAge( int value )
{
age = value;
}

public String getUsername() { return username; }

public String getEmail() { return email; }

public int getAge() { return age; }

}

The method names must be exactly as shown. Once you have defined the class, compile it and make sure it is available in the web-server's classpath. The server may also define special folders where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder. If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running. (If you are not familiar with setting/changing classpath, see notes on changing classpath.)

Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry.

Now let us change "SaveName.jsp" to use a bean to collect the data.





Continue



All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! The useBean tag will look for an instance of the "user.UserData" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session.

The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!

Let us modify NextPage.jsp to retrieve the data from bean..




You entered

Name: <%= user.getUsername() %>

Email: <%= user.getEmail() %>

Age: <%= user.getAge() %>




Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean.

We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag. But in the next tutorial, we will actually use SaveName.jsp as an error handler that automatically forwards the request to NextPage.jsp, or asks the user to correct the erroneous data.

Exercise: 1) Write a JSP/HTML set that allows a user to enter the name of a system property, and then displays the value returned by System.getProperty for that property name (handle errors appripriately.) 2) Go back to the exercises where you manually modified boolean variables. Instead of a boolean variable, make these come from a HIDDEN form field that can be set to true or false.
n a typical web site, a visitor might visit several pages and perform several interactions.

If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP.

A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site.

Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these.

First we have a form, let us call it GetName.html




What's your name?






The target of the form is "SaveName.jsp", which saves the user's name in the session. Note the variable "session". This is another variable that is normally made available in JSPs, just like out and request variables. (In the @page directive, you can indicate that you do not need sessions, in which case the "session" variable will not be made available.)

<% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %>


Continue



The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.



Hello, <%= session.getAttribute( "theName" ) %>



If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of.

The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded.

Exercise: Add another attribute "age" to the above example.

Mixing Scriptlets and HTML

We have already seen how to use the "out" variable to generate HTML output from within a scriptlet. For more complicated HTML, using the out variable all the time loses some of the advantages of JSP programming. It is simpler to mix scriptlets and HTML.

Suppose you have to generate a table in HTML. This is a common operation, and you may want to generate a table from a SQL table, or from the lines of a file. But to keep our example simple, we will generate a table containing the numbers from 1 to N. Not very useful, but it will show you the technique.

Here is the JSP fragment to do it:


<% for ( int i = 0; i <>




<% } %>
Number <%= i+1 %>


You would have to supply an int variable "n" before it will work, and then it will output a simple table with "n" rows.

The important things to notice are how the %> and <% characters appear in the middle of the "for" loop, to let you drop back into HTML and then to come back to the scriptlet. The concepts are simple here -- as you can see, you can drop out of the scriptlets, write normal HTML, and get back into the scriptlet. Any control expressions such as a "while" or a "for" loop or an "if" expression will control the HTML also. If the HTML is inside a loop, it will be emitted once for each iteration of the loop. Another example of mixing scriptlets and HTML is shown below -- here it is assumed that there is a boolean variable named "hello" available. If you set it to true, you will see one output, if you set it to false, you will see another output. <% if ( hello ) { %>

Hello, world
<% } else { %>

Goodbye, world
<% } %>

It is a little difficult to keep track of all open braces and scriptlet start and ends, but with a little practice and some good formatting discipline, you will acquire competence in doing it.

Exercise: Make the above examples work. Write a JSP to output all the values returned by System.getProperties with "
" embedded after each property name and value. Do not output the "
" using the "out" variable.

Reading Request Information

When an HTTP client such as web browser sends a request to a wen server, along with the request it also sends some HTTP variables like Remote address, Remote host, Content type etc. In some cases these variables are useful to the programmers. So here is the code of the jsp file which prints the HTTP request information:

<%@page contentType="text/html" import="java.util.*" %>

Request Information:

Request Method: <%=request.getMethod()%>
Request URI: <%=request.getRequestURI()%>
Request Protocol: <%=request.getProtocol()%>
Path Info: <%=request.getPathInfo()%>
Path translated: <%=request.getPathTranslated()%>
Query String: <%=request.getQueryString()%>
Content length: <%=request.getContentLength()%>
Content type: <%=request.getContentType()%>
Server name: <%=request.getServerName()%>
Server port: <%=request.getServerPort()%>
Remote user: <%=request.getRemoteUser()%>
Remote address: <%=request.getRemoteAddr()%>
Remote host: <%=request.getRemoteHost()%>
Authorization scheme: <%=request.getAuthType()%>

Till now you learned about the JSP syntax, now I will show you how to create a simple dynamic JSP page that prints the current date and time. So the following code accomplish this:










<%@page contentType="text/html" import="java.util.*" %>

















Date Example
Current Date
and time is:


<%= new java.util.Date() %>






The heart of this example is Date() function of the java.util package which returns the current data and time.

In the JSP Declaratives

<%@page contentType="text/html" import="java.util.*" %>

we are importing the java.util package and following JSP Expression code

<%= new java.util.Date() %>

prints the current date on the page.

Date Example in JSP

Till now you learned about the JSP syntax, now I will show you how to create a simple dynamic JSP page that prints the current date and time. So the following code accomplish this:

<%@page contentType="text/html" import="java.util.*" %>




"center">

"0" cellpadding="0" cellspacing
=
"0" width="460" bgcolor="#EEFFCA">






"100%">"6" color
=
"#008000"> Date Example
"100%"> Current Date
and time is:
"#FF0000">


<%= new java.util.Date() %>





The heart of this example is Date() function of the java.util package which returns the current data and time.

In the JSP Declaratives

<%@page contentType="text/html" import="java.util.*" %>

we are importing the java.util package and following JSP Expression code

<%= new java.util.Date() %>

prints the current date on the page.

JSP Scriptlets

Syntax of JSP Scriptles are:

<%
//java codes
%>

JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are:

  • request:
    request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request.
    Example:
    <%
    //java codes
    String userName=null;
    userName=request.getParameter("userName");
    %>
  • response:
    response is subclass of HttpServletResponse.
  • session:
    session represents the HTTP session object associated with the request.
  • out:
    out is an object of output stream and is used to send any output to the client.
Other variable available to the scriptlets are pageContext, application,config and exception.

INTRODUCTION TO JSP EXPRESSIONS

Syntax of JSP Expressions are:

<%="Any thing" %>

JSP Expressions start with

Syntax of JSP Scriptles are with <%= and ends with %>. Between these this you can put anything and that will converted to the String and that will be displayed.

Example:
<%="Hello World!" %>
Above code will display 'Hello World!'.

JSP DECLARATIVES

Syntax of JSP Declaratives are:

<%!
//java codes
%>

JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP Declaratives. Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page.

Example:

<%@page contentType="text/html" %>

<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>

Values of Cnt are:

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

The above example prints the value of variable cnt.
To execute the code click below.

JSP Tags

In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are:
  1. Directives
    In the directives we can import packages, define error handling pages or the session information of the JSP page.
  2. Declarations
    This tag is used for defining the functions and variables to be used in the JSP.
  3. Scriplets
    In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.
  4. Expressions
    We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.
Now we will examine each tags in details with examples. DIRECTIVES

Syntax of JSP directives is:

<%@directive attribute="value" %>

Where directive may be:

  1. page: page is used to provide the information about it.
    Example: <%@page language="java" %>
  2. include: include is used to include a file in the JSP page.
    Example: <%@ include file="/header.jsp" %>
  3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).
    Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

and attribute may be:

  1. language="java"
    This tells the server that the page is using the java language. Current JSP specification supports only java language.
    Example: <%@page language="java" %>
  2. extends="mypackage.myclass"
    This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
    Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>
  3. session="true"
    When this value is true session data is available to the JSP page otherwise not. By default this value is true.
    Example: <%@page language="java" session="true" %>
  4. errorPage="error.jsp"
    errorPage is used to handle the un-handled exceptions in the page.
    Example: <%@page language="java" session="true" errorPage="error.jsp" %>
  5. contentType="text/html;charset=ISO-8859-1"
    Use this attribute to set the mime type and character set of the JSP.
    Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>

JSP ARCHITECTURE

JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.

javax.servlet.jsp package defines two interfaces:

*

JSPPage
*

HttpJspPage

These interfaces defines the three methods for the compiled JSP page. These methods are:

* jspInit()
* jspDestroy()
* _jspService(HttpServletRequest request,HttpServletResponse response)


In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.

JSP

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets, they have an evolutionary relationship and can be used in a cooperative and complementary manner.

Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment.

Evolution of Web Applications

Over the last few years, web server applications have evolved from static to dynamic applications. This evolution became necessary due to some deficiencies in earlier web site design. For example, to put more of business processes on the web, whether in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional web site design technologies are not enough. The main issues, every developer faces when developing web applications, are:

1. Scalability - a successful site will have more users and as the number of users is increasing fastly, the web applications have to scale correspondingly.

2. Integration of data and business logic - the web is just another way to conduct business, and so it should be able to use the same middle-tier and data-access code.

3. Manageability - web sites just keep getting bigger and we need some viable mechanism to manage the ever-increasing content and its interaction with business systems.

4. Personalization - adding a personal touch to the web page becomes an essential factor to keep our customer coming back again. Knowing their preferences, allowing them to configure the information they view, remembering their past transactions or frequent search keywords are all important in providing feedback and interaction from what is otherwise a fairly one-sided conversation.

Apart from these general needs for a business-oriented web site, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized. The main characteristics of today's dynamic web server applications are as follows:

1. Serve HTML and XML, and stream data to the web client

2. Separate presentation, logic and data

3. Interface to databases, other Java applications, CORBA, directory and mail services

4. Make use of application server middleware to provide transactional support.

5. Track client sessions

Now let us have a look on the role of Java technology and platform in this regard.

Java's Role for Server Applications

Sun Microsystems, having consulted many expert partners from other related IT industries, has come out with a number of open APIs for the technologies and services on server side. This collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification provides a platform for enterprise applications, with full API support for enterprise code and guarantees of portability between server implementations. Also it brings a clear division between code which deals with presentation, business logic and data.

The J2EE specification meets the needs of web applications because it provides:

1. Rich interaction with a web server via servlets and built-in support for sessions available in both servlets and EJBs.

2. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.

3. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs

4. Flexible template-based output using JSP and XML

This family of APIs mean that the final web page can be generated from a user input request, which was processed by a servlet or JSP and a session EJB, which represents the user's session with the server, using data extracted from a database and put into an entity EJB. Thus, the Java revolution of portable code and open APIs is married with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. This makes server-side Java a very exciting area.

JavaServer Pages - An Overview

The JavaServer Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML, XHTML and XML. A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.

There are many JSP tags such as:

  • JSP directive denoted by <%@,

    2. scriplets indicated by <% ... %> tags and

  • directive includes the contents of the file sample.html in the response at that point.

To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.

This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory. Thus when a request comes for a servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.

The Components of JSPs

JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP tags.

1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.

2. Attribute values in the tag always appear quoted. The special strings ' and " can be used if quotes are a part of the attribute value itself.

Any whitespace within the body text of a document is not significant, but is preserved, which means that any whitespace in the JSP being translated is read and preserved during translation into a servlet.

The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.

JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:

1. Elements that are processed on the server

2. Template data or everything other than elements, that the engine processing the JSP engines.

Element data or that part of the JSP which is processed on the server, can be classified into the following categories:

1. Directives

2. Scripting elements

3. Standard actions

JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have scope of the entire JSP file. That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized by the @ character within the tag and the general syntax is:

The three directives are page, include and taglib.

Scripting elements are used to include scripting code (Java code) within the JSP. They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression. The three types of scripting element are: Declaration, Scriptlets and Expressions.

A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.

A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the scriptlet actually does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.

An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.

Standard actions are specific tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.

How JSP and JSP Container function

A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in a application server. When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.

The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. The servlet class generated at the end of the translation process must extend a superclass that is either

1. specified by the JSP author through the use of the extends attribute in the page directive or

2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.

Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.

The javax.servlet.jsp.JspPage interface contains two methods:

1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.

2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.

The javax.servlet.jsp.HttpJspPage interface contains one method:

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.

JSP Architecture

There are two basic ways of using the JSP technology. They are the client/server (page-centric) 2-tier approach and the N-tier approach (dispatcher).

The Page-Centric Approach

Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work. With the arrival of Servlets technology, 2-tier applications could also be developed using Java programming language. This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question.

Page-view - This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed a number of benefits. It is very straightforward and is a low-overhead approach from a developerment perspective. All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.

The big trade-off here is in the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.

Page-view with bean - This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which can be comfortably owned by an individual in a web-production role, since it encapsulates mostly markup tags.

The Dispatcher Approach

In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view and service to workers.

In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with the back end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resources, support transactions and access to underlying security mechanisms, thus addressing the resource sharing and performance issues of the 2-tier approach.

The first step in N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories.

Front end JSPs or Servlets manage application flow and business logic evaluation. They act as a point to intercept the HTTP requests coming from the users. They provide a single entry point to an application, simplifying security management and making application state easier to maintain.

Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being presentation of dynamic content. They contain only presentation and rendering logic.

These categories resemble to the Modal-View design pattern, where the front-end components is the model and the presentation component the view. In this approach, JSPs are used to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts as the controller and is in charge of the request processing and the creation of any beans or objects used by the presentation JSP, as well as deciding, depending on the user's actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply responsible for retrieving any objects or beans that may have been previously created by the Servlet and extracting the dynamic content for insertion within static templates.

Benefits of JSP

One of the main reasons why the JavaServer Pages technology has evolved into what it is today and it is still evolving is the overwhelming technical need to simplify application design by separating dynamic content from static template display data. Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer. The JSP technology is blessed with a number of exciting benefits, which are chronicled as follows:

1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. That is, JSP pages perform perfectly without any hassle on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server.

2. The JSP technology emphasizes the use of reusable components. These components can be combined or manipulated towards developing more purposeful components and page design. This definitely reduces development time apart from the At development time, JSPs are very different from Servlets, however, they are precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.

Conclusion

JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise's needs for web applications providing secure transactions in an open platform. J2EE technology as a whole makes it easy to develop, deploy and use web server applications instead of mingling with other technologies such as CGI and ASP. There are many tools for facilitating quick web software development and to easily convert existing server-side technologies to JSP and Servlets.

Many application server vendors are aggressively deploying JSP within their products. This results in developing robust e-commerce applications as JSP provides XML functionality and scalability. By providing a clear separation between content and coding, JSP solves many problems attached with existing server-side applications.