javax.servlet.jsp Package
February 18, 2008 by muralis
Check here and read about javax.servlet.jsp package
Saving Data in a JSP Page
When a JSP page needs to save data for its processing, it must specify a location, called the scope. There are four scopes available - page, request, session, and application. Page - scoped data is accessible only within the JSP page and is destroyed when the page has finished generating its output for the request. Request-scoped data is associated with the request and destroyed when the request is completed. Session-scoped data is associated with a session and destroyed when the session is destroyed. Application-scoped data is associated with the web application and destroyed when the web application is destroyed. Application-scoped data is not accessible to other web applications.
Data is saved using a mechanism called attributes. An attribute is a key/value pair where the key is a string and the value is any object. It is recommended that the key use the reverse domain name convention (e.g., prefixed with com.mycompany) to minimize unexpected collisions when integrating with third party modules.
This example uses attributes to save and retrieve data in each of the four scopes:
Implementing a Form in a JSP PageThere are many different strategies for implementing a form. Some strategies involve a JSP page that shows the form and another to show field validation errors. This example combines both pages in one since in most cases, the page that shows validation errors looks like the original page except for error messages next to the fields with errors.
When the page is first shown, no validation is done. When the form is submitted, the new values are submitted to the same page except that this time, the page will validate the values. If the values are all valid, the form is processed and the browser is redirected to a success page.
The above behavior is implemented using a request parameter called process. If set to “true”, the page will validate the values and possibly process the form; otherwise, the page simply shows a blank form. The request parameter is added when the user submits the form.
It is good practice to avoid placing the form validation code in the JSP page. The example encapsulates the validation and form processing code in a bean called com.mycompany.MyForm. When the form is submitted, an instance of this bean is instantiated and loaded with the submitted values for validation and processing.
It is also considered good practice not to place error messages in business objects such as in the MyForm class. The strategy used in this example is to create and store a map of error messages in the page instance and supply this map to every new MyForm instance to use. In this way, all presentation related information is contained in one JSP file. This makes it easier to maintain and potentially localize the page. Another strategy is to use resource bundles. However, unless all content on the page is moved in the resource bundle, it may be simpler to keep the error messages in the page to avoid having to manage two sources of content.
<jsp:setProperty name=”form” property=”errorMessages” value=”/>
<form action=” method=”POST”>
Email: <input type=”TEXT” name=”email” value=”>
Zipcode: <input type=”TEXT” name=”zipcode” value=”>
Here is the code for the com.mycompany.MyForm bean:
package com.mycompany;
import java.util.*;
public class MyForm {
/* The properties */
String email = “”;
String zipcode = “”;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email.trim();
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode.trim();
}
/* Errors */
public static final Integer ERR_EMAIL_ENTER = new Integer(1);
public static final Integer ERR_EMAIL_INVALID = new Integer(2);
public static final Integer ERR_ZIPCODE_ENTER = new Integer(3);
public static final Integer ERR_ZIPCODE_INVALID = new Integer(4);
public static final Integer ERR_ZIPCODE_NUM_ONLY = new Integer(5);
// Holds error messages for the properties
Map errorCodes = new HashMap();
// Maps error codes to textual messages.
// This map must be supplied by the object that instantiated this bean.
Map msgMap;
public void setErrorMessages(Map msgMap) {
this.msgMap = msgMap;
}
public String getErrorMessage(String propName) {
Integer code = (Integer)(errorCodes.get(propName));
if (code == null) {
return “”;
} else if (msgMap != null) {
String msg = (String)msgMap.get(code);
if (msg != null) {
return msg;
}
}
return “Error”;
}
/* Form validation and processing */
public boolean isValid() {
// Clear all errors
errorCodes.clear();
// Validate email
if (email.length() == 0) {
errorCodes.put(”email”, ERR_EMAIL_ENTER);
} else if (!email.matches(”.+@.+\\..+”)) {
errorCodes.put(”email”, ERR_EMAIL_INVALID);
}
// Validate zipcode
if (zipcode.length() == 0) {
errorCodes.put(”zipcode”, ERR_ZIPCODE_ENTER);
} else if (zipcode.length() != 5) {
errorCodes.put(”zipcode”, ERR_ZIPCODE_INVALID);
} else {
try {
int i = Integer.parseInt(zipcode);
} catch (NumberFormatException e) {
errorCodes.put(”zipcode”, ERR_ZIPCODE_NUM_ONLY);
}
}
// If no errors, form is valid
return errorCodes.size() == 0;
}
public boolean process() {
if (!isValid()) {
return false;
}
// Process form…
// Clear the form
email = “”;
zipcode = “”;
errorCodes.clear();
return true;
}
}
Implementing a Form That Prevents Duplicate Submissions in a JSP PageAfter the user submits a form for processing, it is possible for the user to inadvertently hit the back button and resubmit the form again. ‘Implementing a Form in a JSP Page’ implements such a form. It is possible to prevent this possibility if necessary. The strategy involves the use of a timestamp that is saved in the session as well as embedded on the form. When the form is submitted for processing, the timestamp in the form is compared to the value saved in the session. If the timestamps do not match, it is assumed that either the form has expired or has been submitted.
This example builds on the one in ‘Implementing a Form in a JSP Page’. Refer to that example for more information about this example.
<jsp:setProperty name=”form” property=”errorMessages” value=”/>
<form action=” method=”POST”>
Email: <input type=”TEXT” name=”email” value=”>
Zipcode: <input type=”TEXT” name=”zipcode” value=”>
<input type=”HIDDEN” name=”timestamp” value=”">
Preventing the Creation of a Session in a JSP PageBy default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.
The page directive is used to prevent a JSP page from automatically creating a session:
…
Including a File in a JSP PageTo include an HTML or JSP fragment in a JSP file, the include directive is used. The effect is essentially equivalent to replacing the directive with the contents of the included file. This means that an included fragment can access any objects defined in the main JSP page.
The include file specified by include directive is always relative to the file containing the include directive. For example, if a file A.jsp includes dir/B.jsp which in turn includes C.jsp, C.jsp is assumed to be in the directory dir.
This example includes a file called relativeFragment.jsp which is located in the same directory as the current file:
This example includes a file called /absoluteFragment.jsp which is located relative to the web application’s root:
At the time the main JSP page is accessed, the include directive permanently captures the current contents of an included file. Changes to the included file will not affect the results of the main JSP page. If the application depends on capturing the contents of the included file at the time of each request, then an include action should be used.
These examples demonstrate how to use an include action to dynamically include the contents of a relative or absolute fragment at every request:
It is also possible to dynamically choose the file to include. This example determines the file to include from a request parameter:
<jsp:include page=” />
Passing Parameters to Another JSP PageAn include action (see ‘Including a File in a JSP Page’) executes the included JSP page and appends the generated output onto its own output stream. Request parameters parsed from the URL’s query string are available not only to the main JSP page but to all included JSP pages as well. It is possible to temporarily override a request parameter or to temporarily introduce a new request parameter when calling a JSP page. This is done by using the jsp:param action.
In this example, param1 is specified in the query string and is automatically made available to the callee JSP page. param2 is also specified in the query string but is overridden by the caller. Notice that param2 reverts to its original value after the call. param3 is a new request parameter created by the caller. Notice that param3 is only available to the callee and when the callee returns, param3 no longer exists. Here is the caller JSP page:
Caller:
param1:
param2:
param3:
Here is the JSP page being called:
Callee:
param1:
param2:
param3:
If the example is called with the URL:
http://hostname.com?param1=a¶m2=b
the output would be:
Callee:
param1: a
param2: value2
param3: value3
Caller:
param1: a
param2: b
param3: null
Using a Bean in a JSP PageTo use a bean in a JSP page, three attributes must be supplied - an id, which provides a local name for the bean, the bean’s class name, which is used to instantiate the bean if it does not exit, and a scope, which specifies the lifetime of the bean.
There are four scopes available - page, request, session, and application. A page-scoped bean is available only within the JSP page and is destroyed when the page has finished generating its output for the request. A request-scoped bean is destroyed when the response is sent. A session-scoped bean is destroyed when the session is destroyed. An application-scoped bean is destroyed when the web application is destroyed.
This example retrieves a session-scoped bean and makes it available using the id myBean. The bean is automatically created if it does not exist:
If it is necessary to initialize the bean after it is created, the initialization code can be placed in the body of the jsp:useBean action. The body will not be executed if the bean already exists. Here is an example:
The value of a bean property can be included in the generated output using the jsp:getProperty action:
The jsp:useBean action also declares a local Java variable to hold the bean object. The name of the local variable is exactly the value of the id attribute. Here is an example that accesses the bean within a scriptlet:
<%
if (myBean.getProp1() % 2 == 0) {
out.println(”“+myBean.getProp1()+”“);
} else {
out.println(”“+myBean.getProp1()+”“);
}
%>
Here is the bean used in the example:
package com.mycompany;
public class MyBean {
// Initialize with random values
int prop1 = (int)(Integer.MAX_VALUE*Math.random());
String prop2 = “”+Math.random();
public int getProp1() {
return prop1;
}
public void setProp1(int prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
}
Commenting a JSP PageTwo types of comments are allowed in a JSP page - - hidden and output comments. A hidden comment will not appear in the generated output whereas an output comment will appear in the generated output.
This example shows a hidden comment:
A restriction for hidden comments is that the comment string cannot contain the character sequence –.
This example shows an output comment:
Similar to hidden comments, output comments cannot contain the character sequence –. Output comments can contain dynamic content:
<!– This page was generated on –>
Output:
Handling Unhandled Exceptions in a JSP PageA JSP page should handle any exceptions that might arise from the use of scriptlets, expressions, or other JSP elements. However, there is always a chance that something unexpected happens and an unhandled exception is thrown. A JSP page can specify a specific page to be included when an unhandled exception is thrown. This error page would typically show an error message to the user, log the error message, and possibly notify an administrator of the problem.
Author’s note: Some developers design their pages to throw an exception (e.g. NumberFormatException) if the user’s input is invalid and then have the error page handle the exception. However, if an unhandled exception does arise, the error page can become confused. I prefer to handle input errors by explicitly checking for them and then including ( ‘Including a File in a JSP Page’ ) the appropriate error page if necessary.
A JSP page specifies the error page with the page directive and errorPage attribute. When an unhandled exception occurs, any unflushed output in the output stream is discarded and the error page is immediately executed. Here is an example of JSP page specifying erropage.jsp to be the error page:
The error page indicates that it is an error page with the page directive and isErrorPage attribute. This makes the unhandled exception available in a variable called exception. Here is an example of an error page that simply prints the name of the unhandled exception:
An unexcepted error occurred. The name of the exception is: