Thursday, January 8, 2009

One of Murthy's bad statement.

'We won't hire anybody from Satyam' - Infosys

Friends this is the statement made by Mr Narayan Murthy founder Infosys.

What are your opinions on this? I have written my point of view please note that this is my own opinion and nothing is related to this.Here goes my opinion about his statement:

"
Mr.Narayan Murty even though I m not an employee of Satyam but I would like to share my point of view on your statement.See what all the things happened that are happened behind the curtains of employees by idiot Raju,employees doesn't even know whats that internal matter happening around them,as this is the global recession time many of the employees has decided not to look for a job change instead they had stick to there jobs.But when the world got to know about the fraudster Raju they also came to about the situation and are in search of a new job.As a human being even if you don't want to take any employees of Satyam,you shouldn't made such a non-sense statement publicly.It should be your companies internal matter.Why the hell are you thinking yourself as a superior Your not a God keep this in your mind.God will help them out in there trouble time.One or another day you will also have to see this kind of hard day in your life,because its a cycle whoever goes up will have to come down one or another day.I know why are you making such a bull shit statements just to get there most of their clients into your pocket,this is what is your business strategy.Are you in a mindset that Your company is only place to work for IT and ITES employees Open your eyes Murty there are many other good companies which only looks for talent not the percentage like yours hell company.Our traditions teach us that whoever comes to our door and ask for water no matter who he is even he is our enemy we will give him water.But you being Indian shame on you old man.Shame on your Infosys. "

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.