JSP Introduction
JSP Introduction
By
Short Course| Exercises | Download
Concepts
After completing this module you will understand the:
● Advantages of JSP technology
● JSP architecture
Objectives
By the end of this module you will be able to:
● Manage session-related information from JSP
Prerequisites
A general familiarity with object-oriented programming concepts
and the Java programming language. If you are not familiar with
these capabilities, see the Java Tutorial. The exercises require the
ability to modify and build simple Java programs and HTML-like
pages. It may also help to understand the fundamentals of Web
computing and servlets. For help on servlet-specific issues, see the
earlier Fundamentals of Java Servlets course, though that is based
on the Servlets 2.1 API, instead of the newer 2.2 version.
Reader Feedback
Submit Reset
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Exercise Outline
● About Exercises
❍ The Anatomy of an Exercise
❍ Exercise Design Goals
● JavaServer Pages Fundamentals Exercises
❍ Installing and Configuring Tomcat
❍ Exception Handling in JSP
❍ Understanding JSP Object Scope
❍ Form Processing Using JSP
Welcome to the jGuru exercises for the JavaServer PagesTM
Fundamentals Short Course.
These exercises demonstrate how to use Tomcat -- the JSP 1.1
Reference Implementation, as well as how to design, implement,
and deploy JSPs.
When you finish these exercises, you will know the basic steps for
designing, compiling, and deploying JSP web components.
About Exercises
A jGuru exercise is a flexible exercise that provides varying levels
of help according to the student's needs. Some students may
complete the exercise using only the information and the task list
in the exercise body; some may want a few hints (Help); while
others may want a step-by-step guide to successful completion
(Solution). Since complete solutions are provided in addition to
help, students can skip an exercise and still complete later
exercises that required the skipped one(s).
Educational goal(s):
❍ Install Tomcat.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Course Outline
● Introduction
❍ JSP Advantages
❍ Comparing JSP with ASP
❍ JSP or Servlets?
● JSP Architecture
● JSP Access Models
● JSP Syntax Basics
❍ Directives
■ Page Directive
■ Include Directive
❍ Declarations
❍ Expressions
❍ Scriptlets
❍ Comments
● Object Scopes
● JSP Implicit Objects
● Synchronization Issues
● Exception Handling
● Session Management
● Standard Actions
❍ Using JavaBean Components
❍ Forwarding Requests
■ Request Chaining
❍ Including Requests
● Web Sites
● Documentation and Specs
● Articles
Introduction
While there are numerous technologies for building web applications that serve
dynamic content, the one that has really caught the attention of the
development community is JavaServer PagesTM (JSPTM). And not without ample
reason either. JSP not only enjoys cross-platform and cross-Web-server support,
but effectively melds the power of server-side Java technology with the
WYSIWYG features of static HTML pages.
JSP pages typically comprise of:
● Static HTML/XML components.
JSP Advantages
Separation of static from dynamic content: With servlets, the logic for
generation of the dynamic content is an intrinsic part of the servlet itself, and is
closely tied to the static presentation templates responsible for the user
interface. Thus, even minor changes made to the UI typically result in the
recompilation of the servlet. This tight coupling of presentation and content
results in brittle, inflexible applications. However, with JSP, the logic to generate
the dynamic content is kept separate from the static presentation templates by
encapsulating it within external JavaBeans components. These are then created
and used by the JSP page using special tags and scriptlets. When a page
designer makes any changes to the presentation template, the JSP page is
automatically recompiled and reloaded into the web server by the JSP engine.
Write Once Run Anywhere: JSP technology brings the "Write Once, Run
Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily
across platforms, and across web servers, without any changes.
Dynamic content can be served in a variety of formats: There is nothing that
mandates the static template data within a JSP page to be of a certain format.
Consequently, JSP can service a diverse clientele ranging from conventional
browsers using HTML/DHTML, to handheld wireless devices like mobile phones
and PDAs using WML, to other B2B applications using XML.
Recommended Web access layer for n-tier architecture: Sun's J2EETM Blueprints,
Although the features offered by JSP may seem similar to that offered by
Microsoft's Active Server Pages (ASP), they are fundamentally different
technologies, as shown by the following table:
JavaServer Pages Active Server Pages
Most popular web
servers including Native support only within Microsoft
Web Server Apache, Netscape, and IIS or Personal Web Server. Support
Support Microsoft IIS can be for select servers using third-party
easily enabled with products.
JSP.
Platform independent. Is fully supported under Windows.
Platform Runs on all Deployment on other platforms is
Support Java-enabled cumbersome due to reliance on the
platforms. Win32-based component model.
Relies on reusable,
cross-platform
Component components like Uses the Win32-based COM
Model JavaBeans, Enterprise component model.
JavaBeans, and
custom tag libraries.
Can use the Java
Supports VBScript and JScript for
Scripting programming language
scripting.
or JavaScript.
Works with the Java Can work with the Windows NT
Security
security model. security architecture.
Database Uses JDBC for data Uses Active Data Objects for data
Access access. access.
Customizable JSP is extensible with Cannot use custom tag libraries and is
Tags custom tag libraries. not extensible.
JSP or Servlets?
It is true that both servlets and JSP pages have many features in common, and
can be used for serving up dynamic web content. Naturally, this may cause
some confusion as to when to opt for one of the technologies over the other.
Luckily, Sun's J2EE Blueprints offers some guidelines towards this.
itself is a specialized servlet running under the control of the servlet engine.
Since JSP only deals with textual data, you will have to continue to use servlets
when communicating with Java applets and applications.
Use JSP to develop typical web applications that rely upon dynamic content. JSP
should also be used in place of proprietary web server extensions like
server-side includes as it offers excellent features for handling repetitive
content.
Exercise
1. Installing and Configuring Tomcat
JSP Architecture
The purpose of JSP is to provide a declarative, presentation-centric method of
developing servlets. As noted before, the JSP specification itself is defined as a
standard extension on top the Servlet API. Consequently, it should not be too
surprisingly that under the covers, servlets and JSP pages have a lot in
common.
Typically, JSP pages are subject to a translation phase and a request processing
phase. The translation phase is carried out only once, unless the JSP page
changes, in which case it is repeated. Assuming there were no syntax errors
within the page, the result is a JSP page implementation class file that
implements the Servlet interface, as shown below.
The translation phase is typically carried out by the JSP engine itself, when it
receives an incoming request for the JSP page for the first time. Note that the
JSP 1.1 specification also allows for JSP pages to be precompiled into class files.
Precompilation may be especially useful in removing the start-up lag that occurs
when a JSP page delivered in source form receives the first request from a
client. Many details of the translation phase, like the location where the source
and class files are stored are implementation dependent. The source for the
class file generated by Tomcat for this example JSP page (shown in the above
figure) is as follows:
package jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import org.apache.jasper.runtime.*;
import java.beans.*;
import org.apache.jasper.JasperException;
import java.text.*;
import java.util.*;
static {
}
public _0005cjsp_0005cjsptest_0002ejspjsptest_jsp_0( ) {
}
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
// begin
out.write("\r\n<html>\r\n<body>\r\n");
// end
known as Model 1 and Model 2 architectures, for applying JSP technology. These
approaches differ essentially in the location at which the bulk of the request
processing was performed, and offer a useful paradigm for building applications
using JSP technology.
Consider the Model 1 architecture, shown below:
In the Model 1 architecture, the incoming request from a web browser is sent
directly to the JSP page, which is responsible for processing it and replying back
to the client. There is still separation of presentation from content, because all
data access is performed using beans.
Although the Model 1 architecture is suitable for simple applications, it may not
be desirable for complex implementations. Indiscriminate usage of this
architecture usually leads to a significant amount of scriptlets or Java code
embedded within the JSP page, especially if there is a significant amount of
request processing to be performed. While this may not seem to be much of a
problem for Java developers, it is certainly an issue if your JSP pages are
created and maintained by designers--which is usually the norm on large
projects. Another downside of this architecture is that each of the JSP pages
must be individually responsible for managing application state and verifying
authentication and security.
Directives
JSP directives are messages for the JSP engine. They do not directly produce
any visible output, but tell the engine what to do with the rest of the JSP page.
JSP directives are always enclosed within the <%@ ... %> tag. The two primary
directives are page and include. (Note that JSP 1.1 also provides the taglib
directive, which can be used for working with custom tag libraries, although this
isn't discussed here.)
Page Directive
Typically, the page directive is found at the top of almost all of your JSP pages.
There can be any number of page directives within a JSP page, although the
attribute/value pair must be unique. Unrecognized attributes or values result in
a translation error. For example,
makes available the types declared within the included packages for scripting
and sets the page buffering to 16K.
Include Directive
The include directive lets you separate your content into more manageable
elements, such as those for including a common page header or footer. The
page included can be a static HTML page or more JSP content. For example, the
directive:
Declarations
JSP declarations let you define page-level variables to save information or define
supporting methods that the rest of a JSP page may need. While it is easy to get
led away and have a lot of code within your JSP page, this move will eventually
turn out to be a maintenance nightmare. For that reason, and to improve
reusability, it is best that logic-intensive processing is encapsulated as JavaBean
components.
Declarations are found within the <%! ... %> tag. Always end variable
declarations with a semicolon, as any content must be valid Java statements:
Expressions
With expressions in JSP, the results of evaluating the expression are converted
to a string and directly included within the output page. Typically expressions
are used to display simple values of variables or return values by invoking a
bean's getter methods. JSP expressions begin within <%= ... %> tags and do not
include semicolons:
Scriptlets
JSP code fragments or scriptlets are embedded within <% ... %> tags. This Java
code is run when the request is serviced by the JSP page. You can have just
about any valid Java code within a scriptlet, and is not limited to one line of
source code. For example, the following displays the string "Hello" within H1,
H2, H3, and H4 tags, combining the use of expressions and scriptlets:
Comments
Although you can always include HTML comments in JSP pages, users can view
these if they view the page's source. If you don't want users to be able to see
your comments, embed them within the <%-- ... --%> tag:
Object Scopes
Before we look at JSP syntax and semantics, it is important to understand the
scope or visibility of Java objects within JSP pages that are processing a request.
Objects may be created implicitly using JSP directives, explicitly through actions,
or, in rare cases, directly using scripting code. The instantiated objects can be
associated with a scope attribute defining where there is a reference to the
object and when that reference is removed. The following diagram indicates the
various scopes that can be associated with a newly created object:
classes or interfaces typically defined within the Servlet API. The nine implicit
objects:
● request: represents the HttpServletRequest triggering the service invocation.
Request scope.
● response: represents HttpServletResponse to the request. Not used often by
page authors. Page scope.
● pageContext: encapsulates implementation-dependent features in
PageContext. Page scope.
● application: represents the ServletContext obtained from servlet configuration
object. Application scope.
● out: a JspWriter object that writes into the output stream. Page scope.
● config: represents the ServletConfig for the JSP. Page scope.
● page: synonym for the "this" operator, as an HttpJspPage. Not used often by
page authors. Page scope.
● session: An HttpSession. Session scope. More on sessions shortly.
● exception: the uncaught Throwable object that resulted in the error page
being invoked. Page scope.
Note that these implicit objects are only visible within the system generated
_jspService() method. They are not visible within methods you define yourself in
declarations.
Synchronization Issues
By default, the service method of the JSP page implementation class that
services the client request is multithreaded. Thus, it is the responsibility of the
JSP page author to ensure that access to shared state is effectively
synchronized. There are a couple of different ways to ensure that the service
methods are thread-safe. The easy approach is to include the JSP page
directive:
The downside of using this approach is that it is not scalable. If the wait queue
grows due to a large number of concurrent requests overwhelming the
processing ability of the servlet instances, then the client may suffer a
significant delay in obtaining the response.
A better approach is to explicitly synchronize access to shared objects (like
those instances with application scope, for example) within the JSP page, using
scriptlets:
<%
synchronized (application) {
SharedObject foo = (SharedObject)
application.getAttribute("sharedObject");
foo.update(someValue);
application.setAttribute("sharedObject",foo);
}
%>
Exception Handling
JSP provides a rather elegant mechanism for handling runtime exceptions.
Although you can provide your own exception handling within JSP pages, it may
not be possible to anticipate all situations. By making use of the page directive's
errorPage attribute, it is possible to forward an uncaught exception to an error
handling JSP page for processing. For example,
Exercise
2. Exception Handling in JSP
Session Management
By default, all JSP pages participate in an HTTP session. The HttpSession object
can be accessed within scriptlets through the session implicit JSP object. Sessions
are a good place for storing beans and objects that need to be shared across
other JSP pages and servlets that may be accessed by the user. The session
objects is identified by a session ID and stored in the browser as a cookie. If
cookies are unsupported by the browser, then the session ID may be maintained
by URL rewriting. Support for URL rewriting is not mandated by the JSP
specification and is supported only within a few servers. Although you cannot
place primitive data types into the session, you can store any valid Java object
by identifying it by a unique key. For example:
<%
Foo foo = new Foo();
session.putValue("foo",foo);
%>
makes available the Foo instance within all JSP pages and servlets belonging to
the same session. The instance may be retrieved within a different JSP page as:
<%
Foo myFoo = (Foo) session.getValue("foo");
%>
The call to session.getValue() returns a reference to the generic Object type. Thus it
is important to always cast the value returned to the appropriate data type
before using it. It is not mandatory for JSP pages to participate in a session;
they may choose to opt out by setting the appropriate attribute of the page
directive:
The JSP engine holds a live reference to objects placed into the session as long
as the session is valid. If the session is invalidated or encounters a session
timeout, then the objects within are flagged for garbage collection.
Standard Actions
Actions allow you to perform sophisticated tasks like instantiating objects and
communicating with server-side resources like JSP pages and servlets without
requiring Java coding. Although the same can be achieved using Java code
within scriptlets, using action tags promotes reusability of your components and
enhances the maintainability of your application.
When developing beans for processing form data, you can follow a common
design pattern by matching the names of the bean properties with the names of
the form input elements. You also need to define the corresponding getter/setter
methods for each property within the bean. The advantage in this is that you
can now direct the JSP engine to parse all the incoming values from the HTML
form elements that are part of the request object, then assign them to their
corresponding bean properties with a single statement, like this:
Exercises
3. Understanding JSP object scope
4. Form processing using JSP
Forwarding Requests
With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or
static HTML page within the same context as the invoking page. This effectively
halts processing of the current page at the point where the redirection occurs,
although all processing up to that point still takes place:
A <jsp:forward> tag may also have jsp:param subelements that can provide values
for some elements in the request used in the forwarding:
Request Chaining
Request chaining is a powerful feature and can be used to effectively meld JSP
pages and servlets in processing HTML forms, as shown in the following figure:
Consider the following JSP page, say Bean1.jsp, which creates a named instance
fBean of type FormBean, places it in the request, and forwards the call to the
servlet JSP2Servlet. Observe the way the bean is instantiated--here we
automatically call the bean's setter methods for properties which match the
names of the posted form elements, while passing the corresponding values to
the methods.
<html>
<body>
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:getProperty name="fBean" property="name" />
</body>
</html>
Including Requests
The <jsp:include> tag can be used to redirect the request to any static or dynamic
resource that is in the same context as the calling JSP page. The calling page
can also pass the target resource bean parameters by placing them into the
request, as shown in the diagram:
For example:
Web Sites
The following sites have product information as well as whitepapers on JSP and
Servlets:
● Sun Microsystems, JSP Home Page
Articles
Some articles on JSP computing include:
● Advanced Form Processing using JSP by Govind Seshadri (JavaWorld,
March 2000)
● JSP Architectures by Lance Lavandowska, brainopolis.com
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Prerequisites
None
Tasks
1.
Check your system requirements to make sure you have an
adequate hardware and software for installing and running
2. Tomcat.
Download the appropriate version of Tomcat 3.1 from the
3. Apache website.
Where help exists, the task numbers above are linked to the
step-by-step help page.
Solution Source
There is no solution to this exercise. When the tasks in this exercise
have been completed, Tomcat will be installed, running, and available
for the subsequent exercises.
Demonstration
When you complete the tasks in this exercise, Tomcat is installed and
running and available for the subsequent exercises.
Running Tomcat using the command-line command startup should
produce output similar to the following:
myhost> startup
Next Exercise
Exercises
Short Course
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Task 1
Check your system requirements to make sure you have an adequate
hardware and software platform for installing and running Tomcat.
Task 2
Download the appropriate version of Tomcat 3.1 from the Apache
website.
Either grab the ZIP or tar.gz version. Most Windows users should just
grab the ZIP version, though WinZip can read the smaller tar.gz
version.
Task 3
Uncompress the file.
Task 4
Set the environment variable JAVA_HOME to point to the root directory
of your JDK hierarchy. Be sure the Java interpreter is in your PATH
environment variable.
Something like the following will work for Windows, depending upon
SET JAVA_HOME=C:\jdk1.2.2
Task 5
Change to the bin directory and start Tomcat using the command-line
command startup.
myhost> startup
Task 6
Tomcat is now installed and running on port 8080 by default. Explore
the Tomcat documentation within the documentation site to
familiarize yourself more with Tomcat.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Prerequisites
● Installing and Configuring Tomcat
Skeleton Code
● errhandler.jsp
● errorpage.jsp
Tasks
1.
Design a JSP page called errhandler.jsp that can process a POST
2. operation.
Indicate an error page, errorpage.jsp, using the page directive for
3. the JSP page.
Process the posted form elements. Throw an exception if the
value posted for the input element is not equal to an expected
4. value, else print an acknowledgment back to the user.
Develop an error page, errorpage.jsp, which can access the
5. runtime exception.
Solution Source
The following files contain a complete implementation of the JSP error
handling example:
● errhandler.jsp
● errorpage.jsp
Demonstration
From your browser, access the URL
http://localhost:8080/examples/jsp/jdc/errHandling/errhandler.jsp
You should see an HTML form as shown below:
Now, make a selection and submit the form. If you made an incorrect
selection, an exception is thrown and the request is forwarded to the
error handler page, which extracts and displays the exception:
If you made the right choice, you get an acknowledgment from the
JSP page itself:
Next Exercise
Exercises
Short Course
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Task 1
Design a JSP page called errhandler.jsp that can process a POST
operation.
Task 2
Indicate an error page, errorpage.jsp, using the page directive for the
JSP page.
Task 3
Process the posted form elements. Throw an exception if the value
posted for the input element is not equal to an expected value,
else print an acknowledgement back to the user.
Task 4
Develop an error page, errorpage.jsp, which can access the runtime
exception.
Task 5
Deploy the JSP files for the example within Tomcat.
Task 6
Run the error handling example.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Prerequisites
● Installing and Configuring Tomcat
Skeleton Code
● Counter.jsp
● CounterBean.java
Tasks
1.
2. Develop a simple counter bean, CounterBean.java.
3. Compile the counter bean.
4. Deploy the bean within Tomcat.
Develop a JSP page, Counter.jsp, which creates two instances of
the counter bean, one with session scope, and the other with
5. application scope.
6. Deploy the JSP file for the example within Tomcat.
Run the example.
Where help exists, the task numbers above are linked to the
step-by-step help page.
Solution Source
The following files contain a complete implementation of the example
demonstrating JSP variable scope:
● Counter.jsp
● CounterBean.java
Demonstration
From your browser (say, Netscape Navigator), access the URL
http://localhost:8080/examples/jdc/counter/Counter.jsp
Reload the page a few times. You should see the counters
incremented as shown below:
From using a different browser (say, MSIE), access the same URL.
Observe the difference in the counts:
Next Exercise
Exercises
Short Course
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Task 1
Develop a simple counter bean, CounterBean.java.
Task 2
Compile the counter bean.
Task 3
Deploy the bean within Tomcat.
Copy CounterBean.class to
jakarta-tomcat\webapps\examples\WEB-INF\jsp\classes\com\jguru\CounterBean.class.
You will need to create the directories below classes for the package the
bean is in.
Task 4
Develop a JSP page, Counter.jsp, which creates two instances of the
counter bean, one with session scope, and the other with application
scope.
You can use the jsp:useBean tag for instantiating the beans. Make sure
you provide the appropriate scope for the scope attribute.
Task 5
Deploy the JSP file for the example within Tomcat.
Assuming you have installed Tomcat in say, \jakarta-tomcat, copy the JSP
file to \jakarta-tomcat\webapps\examples\jsp\jdc\counter\Counter.jsp
Task 6
Run the example.
(Note: If you use only MSIE, you can simply double click on the browser
icon again to run a second instance of MSIE as a separate process. This
is important to ensure that the browser creates a new session and does
not reuse the one created by an earlier instance.)
Click a few times within both browser to increment the counters for the
beans with session and application scope. Observe the difference
between the two counts.
Copyright 1996-2000 jGuru.com. All Rights Reserved.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
In this exercise, you develop a simple JSP page (form.jsp), which can
process an HTML form containing typical input elements like
textboxes, radio buttons, and checkboxes. You also develop a bean
(FormBean.java), whose property names mirror the input elements of
the form. You will then examine the automatic instantiation of the
bean on a form POST operation, using the introspective features
provided by the JSP engine.
Prerequisites
● Installing and Configuring Tomcat
Skeleton Code
● FormBean.java
● form.jsp
Tasks
1.
You are given the JSP page containing the form. Observe that
the form posts to itself recursively. Instantiate the bean FormBean
when you recognize that a POST operation has taken place. Allow
2. the setter methods to be called on the bean using introspection.
3. Deploy the JSP page within Tomcat.
Develop the bean, FormBean.java, with properties matching the
4. form elements.
5. Compile the bean source FormBean.java.
6. Deploy the bean within Tomcat.
Run the example.
Where help exists, the task numbers above are linked to the
Solution Source
● FormBean.java
● form.jsp
Demonstration
From your browser, access the URL
http://localhost:8080/examples/jsp/jdc/forms/form.jsp.
Fill in data for all the form input elements, before performing a
submit:
On submission, you should see the data you entered extracted from
the bean and displayed beneath the form:
Exercises
Short Course
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
by
Task 1
You are given the JSP page containing the form. Observe that the
form posts to itself recursively. Instantiate the bean FormBean when
you recognize that a POST operation has taken place. Allow the
setter methods to be called on the bean using introspection.
You can use the useBean tag for instantiating the bean. By
indicating property="*" within the setProperty tag, you can direct the
JSP engine to parse all the incoming values from the HTML form
elements that are part of the request object and assign them to
their corresponding bean properties.
Task 2
Deploy the JSP page within Tomcat.
Task 3
Develop the bean, FormBean.java with properties matching the form
elements.
Task 4
Compile the bean source FormBean.java.
Task 5
Deploy the bean within Tomcat.
Copy FormBean.class to
\jakarta-tomcat\webapps\examples\WEB-INF\classes\com\jguru\FormBean.class
Task 6
Run the example.
Fill in data for the form input elements and hit submit. You should
see the data you entered displayed at the bottom of the page.
Copyright 1996-2000 jGuru.com. All Rights Reserved.
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
<html>
<body bgcolor="#c8d8f8">
<form action="/examples/jsp/jdc/forms/form.jsp" method=post>
<center>
<table cellpadding=4 cellspacing=2 border=0>
<tr>
<td valign=top>
<b>First Name</b>
<br>
<input type="text" name="firstName" size=15></td>
<td valign=top>
<b>Last Name</b>
<br>
<input type="text" name="lastName" size=15></td>
</tr>
<tr>
<td valign=top colspan=2>
<b>E-Mail</b>
<br>
<input type="text" name="email" size=20>
<br></td>
</tr>
<tr>
<td valign=top colspan=2>
<b>What languages do you program in?</b>
<br>
<input type="checkbox" name="languages" value="Java">Java
<input type="checkbox" name="languages" value="C++">C++
<input type="checkbox" name="languages" value="C">C<br>
<input type="checkbox" name="languages" value="Perl">Perl
<input type="checkbox" name="languages" value="COBOL">COBOL
<input type="checkbox" name="languages" value="VB">VB<br>
</td>
</tr>
<tr>
<td valign=top colspan=2>
<b>How often can we notify you regarding your interests?</b>
<br>
<input type="radio" name="notify" value="Weekly" checked>Weekly
<input type="radio" name="notify" value="Monthly">Monthly
<input type="radio" name="notify" value="Quarterly">Quarterly
<br></td>
</tr>
<tr>
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>
</table>
</center>
</form>
<%-- Create the bean only when the form is posted --%>
<%
if (request.getMethod().equals("POST")) {
%>
package com.jguru;
public FormBean() {
firstName="";
lastName="";
email="";
languages = new String[] { "1" };
notify="";
}
//write getter methods for firstname, lastname, notify, email and languages
//write setter methods for firstname, lastname, notify, email and languages
<%-- provide appropriate values for the class and scope attributes --%>
<% session_counter.increaseCount();
synchronized(page) {
app_counter.increaseCount();
}
%>
<h3>
Number of accesses within this session:
package com.jguru;
public class CounterBean {
//declare a integer for the counter
<%-- Indicate the location of the error handler using the page tag --%>
<html>
<body>
<form method=post action="errhandler.jsp">
What's the coolest programming language in the known universe?<p>
Java<input type=radio name=language value="JAVA" checked>
C++<input type=radio name=language value="CPP">
Visual Basic<input type=radio name=language value="VB">
<p>
<input type=submit>
</form>
<%
if (request.getMethod().equals("POST")) {
if (request.getParameter("language").equals("JAVA")) {
out.println("<hr><font color=red>You got that right!</font>");
} else {
//thow a new exception initializing it with some message
}
}
%>
</body>
</html>
<%-- Indicate that this is an error page using the page tag --%>
<html>
<body>
<h1>
Error Page
</h1>
<hr>
<h2>
Received the exception:<br>
<font color=red>
<%= exception.toString() %>
</font>
</h2>
</body>
</html>
<% session_counter.increaseCount();
synchronized(page) {
app_counter.increaseCount();
}
%>
<h3>
Number of accesses within this session:
<jsp:getProperty name="session_counter" property="count" />
</h3>
<p>
<h3>
Total number of accesses:
<% synchronized(page) { %>
<jsp:getProperty name="app_counter" property="count" />
<% } %>
</h3>
package com.jguru;
public class CounterBean {
int count;
<%
if (request.getMethod().equals("POST")) {
if (request.getParameter("language").equals("JAVA")) {
out.println("<hr><font color=red>You got that right!</font>");
} else {
throw new Exception("You chose the wrong language!");
}
}
%>
</body>
</html>