0% found this document useful (0 votes)
44 views194 pages

References 60

Uploaded by

Rashid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views194 pages

References 60

Uploaded by

Rashid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 194

Web Component Development Using Java References

© Aptech Ltd Version 1.0 1 of 194


Web Component Development Using Java References

Table of Contents
S#. Session Page No.
1. Session 1: Introduction to Web Applications
● History of Web Applications 4

● The Power of Servlets 11

● Web.xml Deployment Descriptor 15


2. Session 2: Java Servlet
 Servlet API 19

 Page Generation 21

 Introduction to Request Dispatcher 28


3. Session 3: Session Tracking
● Session Tracking 35

● New Session Management Features in Servlet 3.0 42


4. Session 4: Filters and Annotations
● Filtering Requests and Responses 44

● How to upload file Using JSP/Servlet? 48


5. Session 5: Database Access and Event Handling
● Servlet Event Listeners 52
6. Session 6: Asynchronous Servlets and Clients
● Asynchronous Servlet – A new feature in Servlet 3.0 and Java 56
EE 6
7. Session 7: Introduction to JSP
● Scriptlets 65
● JSP Directive: pager and include 67
8. Session 8: JSP Implicit Objects
● Implicit Objects 70
9. Session 9: Standard Actions and JavaBeans
● JavaBeans Concept 72

● Beans and Form Processing 74


10. Session 10: Model-View-Controller Architecture
● Model, View, Controller (MVC) 78
11. Session 11: JSP Expression Language
● Unified Expression Language 81

© Aptech Ltd Version 1.0 2 of 194


Web Component Development Using Java References

12. Session 12: JavaServer Pages Standard Tag Library


● JSTL Set tag examples or <c:set> in JSP – Java J2EE Tutorial 99
13. Session 13: JSP Custom Tags
● JSP Tags 103
14. Session 14: Internationalization
● Servlet Internationalization 184
15. Session 15: Securing Web Applications
● JSP Security in Java 189

© Aptech Ltd Version 1.0 3 of 194


Web Component Development Using Java References

Session 1: Introduction to Web Applications

Histor y of Web Applications

Source http://docstore.mik.ua/orelly/java-ent/servlet/ch01_01.htm
Date of 02/04/2015
Retrieval:

The rise of server-side Java applications is one of the latest and most exciting trends in Java
programming. The Java language was originally intended for use in small, embedded
devices. It was first hyped as a language for developing elaborate client-side web content in
the form of applets. Until recently, Java's potential as a server-side development platform
had been sadly overlooked. Now, Java is coming into its own as a language ideally suited for
server-side development.

Businesses in particular have been quick to recognize Java's potential on the server--Java is
inherently suited for large client/server applications. The cross-platform nature of Java is
extremely useful for organizations that have a heterogeneous collection of servers running
various flavors of the UNIX and Windows operating systems. Java's modern, object-
oriented, memory-protected design allows developers to cut development cycles and
increase reliability. In addition, Java's built-in support for networking and enterprise APIs
provides access to legacy data, easing the transition from older client/server systems.

Java servlets are a key component of server-side Java development. A servlet is a small,
pluggable extension to a server that enhances the server's functionality. Servlets allow
developers to extend and customize any Java-enabled server--a web server, a mail server,
an application server, or any custom server--with a hitherto unknown degree of portability,
flexibility, and ease. But before we go into any more detail, let's put things into perspective.

1.1. History of Web Applications

While servlets can be used to extend the functionality of any Java-enabled server, today
they are most often used to extend web servers, providing a powerful, efficient replacement
for CGI scripts. When you use a servlet to create dynamic content for a web page or
otherwise extend the functionality of a web server, you are in effect creating a web
application. While a web page merely displays static content and lets the user navigate

© Aptech Ltd Version 1.0 4 of 194


Web Component Development Using Java References

through that content, a web application provides a more interactive experience. A web
application can be as simple as a keyword search on a document archive or as complex as
an electronic storefront. Web applications are being deployed on the Internet and on
corporate intranets and extranets, where they have the potential to increase productivity
and change the way that companies, large and small, do business.

To understand the power of servlets, we need to step back and look at some of the other
approaches that can be used to create web applications.

1.1.1. Common Gateway Interface

The Common Gateway Interface, normally referred to as CGI, was one of the first practical
techniques for creating dynamic content. With CGI, a web server passes certain requests to
an external program. The output of this program is then sent to the client in place of a
static file. The advent of CGI made it possible to implement all sorts of new functionality in
web pages, and CGI quickly became a de facto standard, implemented on dozens of web
servers.

It's interesting to note that the ability of CGI programs to create dynamic web pages is a
side effect of its intended purpose: to define a standard method for an information server to
talk with external applications. This origin explains why CGI has perhaps the worst life cycle
imaginable. When a server receives a request that accesses a CGI program, it must create a
new process to run the CGI program and then pass to it, via environment variables and
standard input, every bit of information that might be necessary to generate a response.
Creating a process for every such request requires time and significant server resources,
which limits the number of requests a server can handle concurrently. Figure 1-1 shows the
CGI life cycle.

Figure 1-1. The CGI life cycle

© Aptech Ltd Version 1.0 5 of 194


Web Component Development Using Java References

Even though a CGI program can be written in almost any language, the Perl programming
language has become the predominant choice. Its advanced text-processing capabilities are
a big help in managing the details of the CGI interface. Writing a CGI script in Perl gives it a
semblance of platform independence, but it also requires that each request start a separate
Perl interpreter, which takes even more time and requires extra resources.

Another often-overlooked problem with CGI is that a CGI program cannot interact with the
web server or take advantage of the server's abilities once it begins execution because it is
running in a separate process. For example, a CGI script cannot write to the server's log
file.

1.1.1.1. FastCGI
A company named Open Market developed an alternative to standard CGI named FastCGI.
In many ways, FastCGI works just like CGI--the important difference is that FastCGI creates
a single persistent process for each FastCGI program, as shown in Figure 1-2. This
eliminates the need to create a new process for each request.

Figure 1-2. The FastCGI life cycle

Although FastCGI is a step in the right direction, it still has a problem with process
proliferation: there is at least one process for each FastCGI program. If a FastCGI program
is to handle concurrent requests, it needs a pool of processes, one per request. Considering
that each process may be executing a Perl interpreter, this approach does not scale as well
as you might hope. (Although, to its credit, FastCGI can distribute its processes across
multiple servers.) Another problem with FastCGI is that it does nothing to help the FastCGI
program more closely interact with the server. As of this writing, the FastCGI approach has
not been implemented by some of the more popular servers, including Microsoft's Internet
Information Server. Finally, FastCGI programs are only as portable as the language in which
they're written.

© Aptech Ltd Version 1.0 6 of 194


Web Component Development Using Java References

1.1.1.2. mod_perl

If you are using the Apache web server, another option for improving CGI performance is
using mod_perl. mod_perl is a module for the Apache server that embeds a copy of the Perl
interpreter into the Apache httpd executable, providing complete access to Perl functionality
within Apache. The effect is that your CGI scripts are precompiled by the server and
executed without forking, thus running much more quickly and efficiently. For more
information on mod_perl, see http://perl.apache.org/.

1.1.1.3. PerlEx

PerlEx, developed by ActiveState, improves the performance of CGI scripts written in Perl
that run on Windows NT web servers (Microsoft's Internet Information Server, O'Reilly's
Website Professional, and Netscape's FastTrack Server and Enterprise Server). PerlEx uses
the web server's native API to achieve its performance gains. For more information, see
http://www.activestate.com/plex/.

1.1.2. Other Solutions

CGI/Perl has the advantage of being a more-or-less platform-independent way to produce


dynamic web content. Other well-known technologies for creating web applications, such as
ASP and server-side JavaScript, are proprietary solutions that work only with certain web
servers.

1.1.2.1. Server Extension APIs

Several companies have created proprietary server extension APIs for their web servers. For
example, Netscape provides an internal API called NSAPI (now becoming WAI) and
Microsoft provides ISAPI. Using one of these APIs, you can write server extensions that
enhance or change the base functionality of the server, allowing the server to handle tasks
that were once relegated to external CGI programs. As you can see in

© Aptech Ltd Version 1.0 7 of 194


Web Component Development Using Java References

Figure 1-3, server extensions exist within the main process of a web server.

Figure 1-3. The server extension life cycle

Because server-specific APIs use linked C or C++ code, server extensions can run extremely
fast and make full use of the server's resources. Server extensions, however, are not a
perfect solution by any means. Besides being difficult to develop and maintain, they pose
significant security and reliability hazards: a crashed server extension can bring down the
entire server. And, of course, proprietary server extensions are inextricably tied to the
server API for which they were written--and often tied to a particular operating system as
well.

1.1.2.2. Active Server Pages

Microsoft has developed a technique for generating dynamic web content called Active
Server Pages, or sometimes just ASP. With ASP, an HTML page on the web server can
contain snippets of embedded code (usually VBScript or JScript--although it's possible to
use nearly any language). This code is read and executed by the web server before it sends
the page to the client. ASP is optimized for generating small portions of dynamic content.

Support for ASP is built into Microsoft Internet Information Server Version 3.0 and above,
available for free from http://www.microsoft.com/iis. Support for other web servers is
available as a commercial product from Chili!Soft at http://www.chilisoft.com.

© Aptech Ltd Version 1.0 8 of 194


Web Component Development Using Java References

1.1.2.3. Server-side JavaScript

Netscape too has a technique for server-side scripting, which it calls server-side JavaScript,
or SSJS for short. Like ASP, SSJS allows snippets of code to be embedded in HTML pages to
generate dynamic web content. The difference is that SSJS uses JavaScript as the scripting
language. With SSJS, web pages are precompiled to improve performance.

Support for server-side JavaScript is available only with Netscape FastTrack Server and
Enterprise Server Version 2.0 and above.

1.1.3. Java Servlets

Enter Java servlets. As was said earlier, a servlet is a generic server extension--a Java class
that can be loaded dynamically to expand the functionality of a server. Servlets are
commonly used with web servers, where they can take the place of CGI scripts. A servlet is
similar to a proprietary server extension, except that it runs inside a Java Virtual Machine
(JVM) on the server (see Figure 1-4), so it is safe and portable. Servlets operate solely
within the domain of the server: unlike applets, they do not require support for Java in the
web browser.

Figure 1-4. The servlet life cycle

Unlike CGI and FastCGI, which use multiple processes to handle separate programs and/or
separate requests, servlets are all handled by separate threads within the web server
process. This means that servlets are also efficient and scalable. Because servlets run within
the web server, they can interact very closely with the server to do things that are not
possible with CGI scripts.

© Aptech Ltd Version 1.0 9 of 194


Web Component Development Using Java References

Another advantage of servlets is that they are portable: both across operating systems as
we are used to with Java and also across web servers. As you'll see shortly, all of the major
web servers support servlets. We believe that Java servlets offer the best possible platform
for web application development, and we'll have much more to say about this later in the
chapter.

Although servlets are most commonly used as a replacement for CGI scripts on a web
server, they can extend any sort of server. Imagine, for example, a Java-based FTP server
that handles each command with a separate servlet. New commands can be added by
simply plugging in new servlets. Or, imagine a mail server that allows servlets to extend its
functionality, perhaps by performing a virus scan on all attached documents or handling
mail filtering tasks.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 10 of 194


Web Component Development Using Java References

The Power of Servlets

Source http://docstore.mik.ua/orelly/java-ent/servlet/ch01_03.htm
Date of 02/04/2015
Retrieval:

What makes servlets a viable choice for web development? We believe that servlets offer a
number of advantages over other approaches, including: portability, power, efficiency,
endurance, safety, elegance, integration, extensibility, and flexibility. Let's examine each in
turn.

1.3.1. Portability

Because servlets are written in Java and conform to a well-defined and widely accepted API,
they are highly portable across operating systems and across server implementations. You
can develop a servlet on a Windows NT machine running the Java Web Server and later
deploy it effortlessly on a high-end UNIX server running Apache. With servlets, you can
truly "write once, serve everywhere."

Servlet portability is not the stumbling block it so often is with applets, for two reasons.
First, servlet portability is not mandatory. Unlike applets, which have to be tested on all
possible client platforms, servlets have to work only on the server machines that you are
using for development and deployment. Unless you are in the business of selling your
servlets, you don't have to worry about complete portability. Second, servlets avoid the
most error-prone and inconsistently implemented portion of the Java language: the Abstract
Windowing Toolkit (AWT) that forms the basis of Java graphical user interfaces.

1.3.2. Power

Servlets can harness the full power of the core Java APIs: networking and URL access,
multithreading, image manipulation, data compression, database connectivity,
internationalization, remote method invocation (RMI), CORBA connectivity, and object
serialization, among others. If you want to write a web application that allows employees to
query a corporate legacy database, you can take advantage of all of the Java Enterprise
APIs in doing so. Or, if you need to create a web-based directory lookup application, you
can make use of the JNDI API.

© Aptech Ltd Version 1.0 11 of 194


Web Component Development Using Java References

As a servlet author, you can also pick and choose from a plethora of third-party Java classes
and JavaBeans components. In the future, you'll even be able to use newly introduced
Enterprise JavaBeans components. Today, servlets can use third-party code to handle tasks
such as regular expression searching, data charting, advanced database access, and
advanced networking.

Servlets are also well suited for enabling client/server communication. With a Java-based
applet and a Java-based servlet, you can use RMI and object serialization to handle
client/server communication, which means that you can leverage the same custom code on
the client as on the server. Using CGI for the same purpose is much more complicated, as
you have to develop your own custom protocol to handle the communication.

1.3.3. Efficiency and Endurance

Servlet invocation is highly efficient. Once a servlet is loaded, it generally remains in the
server's memory as a single object instance. Thereafter, the server invokes the servlet to
handle a request using a simple, lightweight method invocation. Unlike with CGI, there's no
process to spawn or interpreter to invoke, so the servlet can begin handling the request
almost immediately. Multiple, concurrent requests are handled by separate threads, so
servlets are highly scalable.

Servlets, in general, are naturally enduring objects. Because a servlet stays in the server's
memory as a single object instance, it automatically maintains its state and can hold on to
external resources, such as database connections, that may otherwise take several seconds
to establish.

1.3.4. Safety

Servlets support safe programming practices on a number of levels. Because they are
written in Java, servlets inherit the strong type safety of the Java language. In addition, the
Servlet API is implemented to be type-safe. While most values in a CGI program, including
a numeric item like a server port number, are treated as strings, values are manipulated by
the Servlet API using their native types, so a server port number is represented as an
integer. Java's automatic garbage collection and lack of pointers mean that servlets are
generally safe from memory management problems like dangling pointers, invalid pointer
references, and memory leaks.

© Aptech Ltd Version 1.0 12 of 194


Web Component Development Using Java References

Servlets can handle errors safely, due to Java's exception-handling mechanism. If a servlet
divides by zero or performs some other illegal operation, it throws an exception that can be
safely caught and handled by the server, which can politely log the error and apologize to
the user. If a C++-based server extension were to make the same mistake, it could
potentially crash the server.

A server can further protect itself from servlets through the use of a Java security manager.
A server can execute its servlets under the watch of a strict security manager that, for
example, enforces a security policy designed to prevent a malicious or poorly written servlet
from damaging the server file system.

1.3.5. Elegance
The elegance of servlet code is striking. Servlet code is clean, object oriented, modular, and
amazingly simple. One reason for this simplicity is the Servlet API itself, which includes
methods and classes to handle many of the routine chores of servlet development. Even
advanced operations, like cookie handling and session tracking, are abstracted into
convenient classes. A few more advanced but still common tasks were left out of the API,
and, in those places, we have tried to step in and provide a set of helpful classes in the
com.oreilly.servlet package.

1.3.6. Integration

Servlets are tightly integrated with the server. This integration allows a servlet to cooperate
with the server in ways that a CGI program cannot. For example, a servlet can use the
server to translate file paths, perform logging, check authorization, perform MIME type
mapping, and, in some cases, even add users to the server's user database. Server-specific
extensions can do much of this, but the process is usually much more complex and error-
prone.

1.3.7. Extensibility and Flexibility

The Servlet API is designed to be easily extensible. As it stands today, the API includes
classes that are optimized for HTTP servlets. But at a later date, it could be extended and
optimized for another type of servlets, either by Sun or by a third party. It is also possible
that its support for HTTP servlets could be further enhanced.

© Aptech Ltd Version 1.0 13 of 194


Web Component Development Using Java References

Servlets are also quite flexible. As you'll see in the next chapter, an HTTP servlet can be
used to generate a complete web page; it can be added to a static page using a
<SERVLET> tag in what's known as a server-side include; and it can be used in cooperation
with any number of other servlets to filter content in something called a servlet chain. In
addition, just before this book went to press, Sun introduced JavaServer Pages, which offer
a way to write snippets of servlet code directly within a static HTML page, using a syntax
that is curiously similar to Microsoft's Active Server Pages (ASP).

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 14 of 194


Web Component Development Using Java References

Web.xml Deployment Descriptor

Source http://www.9lessons.info/2008/09/webxml.html
Date of 02/04/2015
Retrieval:

Web.xml mapping servlet names improve web app's flexibility and security. The deployment
descriptor (DD), provides a "declarative" mechanism for customizing your web applications
without touching source code!

Tomcat Directory Structure

Login.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

© Aptech Ltd Version 1.0 15 of 194


Web Component Development Using Java References

public class Login extends HttpServlet{

public void doGet(HttpServletRequest request,


HttpServletResponse response)throws IOException{

PrintWriter out=response.getWriter();
java.util.Date tody=new java.util.Date();
out.println("output html tags");

}
}

<servlet>Maps internal name to fully-qualified class name.

<servlet-mapping>Maps internal name to public URL name.

web.xml

<servlet-mapping> which servlet should i invoke for this requested URL?

© Aptech Ltd Version 1.0 16 of 194


Web Component Development Using Java References

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
version="2.4">

<servlet>
<servlet-name>Servlet_login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>

<servlet>
<servlet-name>Servlet_inbox</servlet-name>
<servlet-class>inbox</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet_login</servlet-name>
<url-pattern>/signin.do</usr-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Servlet_inbox</servlet-name>
<url-pattern>/view.do</usr-pattern>
</servlet-mapping>

</web-app>

© Aptech Ltd Version 1.0 17 of 194


Web Component Development Using Java References

signin.do file mapping to Login.class. So the client or users to get to the servlet but it's a
made-up name that is NOT the name of the actual servlet class.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 18 of 194


Web Component Development Using Java References

Session 2: Java Servlet

Ser vlet API

Source http://docstore.mik.ua/orelly/java-ent/servlet/ch02_02.htm
Date of 02/04/2015
Retrieval:

Servlets use classes and interfaces from two packages: javax.servlet and
javax.servlet.http. The javax.servlet package contains classes to support generic,
protocol-independent servlets. These classes are extended by the classes in the
javax.servlet.http package to add HTTP-specific functionality. The top-level package name is
javax instead of the familiar java, to indicate that the Servlet API is a standard extension.

Every servlet must implement the javax.servlet.Servlet interface. Most servlets


implement it by extending one of two special classes: javax. servlet.GenericServlet or
javax.servlet.http.HttpServlet. A protocol-independent servlet should subclass
GenericServlet, while an HTTP servlet should subclass HttpServlet, which is itself a
subclass of GenericServlet with added HTTP-specific functionality.

Unlike a regular Java program, and just like an applet, a servlet does not have a main()
method. Instead, certain methods of a servlet are invoked by the server in the process of
handling requests. Each time the server dispatches a request to a servlet, it invokes the
servlet's service() method.

A generic servlet should override its service() method to handle requests as appropriate
for the servlet. The service() method accepts two parameters: a request object and a
response object. The request object tells the servlet about the request, while the response
object is used to return a response. Figure 2-1 shows how a generic servlet handles
requests.

Figure 2-1. A generic servlet handling a request

© Aptech Ltd Version 1.0 19 of 194


Web Component Development Using Java References

In contrast, an HTTP servlet usually does not override the service() method. Instead, it
overrides doGet() to handle GET requests and doPost() to handle POST requests. An HTTP
servlet can override either or both of these methods, depending on the type of requests it
needs to handle. The service() method of HttpServlet handles the setup and dispatching
to all the doXXX() methods, which is why it usually should not be overridden.

Figure 2-2 shows how an HTTP servlet handles GET and POST requests.

Figure 2-2. An HTTP servlet handling GET and POST requests

An HTTP servlet can override the doPut() and doDelete() methods to handle PUT and
DELETE requests, respectively. However, HTTP servlets generally don't touch doHead(),
doTrace(), or doOptions(). For these, the default implementations are almost always
sufficient.

The remainder in the javax.servlet and javax.servlet.http packages are largely


support classes. For example, the ServletRequest and ServletResponse classes in
javax.servlet provide access to generic server requests and responses, while
HttpServletRequest and HttpServletResponse in javax.servlet.http provide access to
HTTP requests and responses. The javax.servlet.http package also contains an
HttpSession class that provides built-in session tracking functionality and a Cookie class that
allows you to quickly set up and process HTTP cookies.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 20 of 194


Web Component Development Using Java References

Page Generation
Source http://docstore.mik.ua/orelly/java-ent/servlet/ch02_03.htm

Date of 02/04/2015
Retrieval:

The most basic type of HTTP servlet generates a full HTML page. Such a servlet has access
to the same information usually sent to a CGI script, plus a bit more. A servlet that
generates an HTML page can be used for all the tasks where CGI is used currently, such as
for processing HTML forms, producing reports from a database, taking orders, checking
identities, and so forth.

2.3.1. Writing Hello World

Example 2-1 shows an HTTP servlet that generates a complete HTML page. To keep things
as simple as possible, this servlet just says "Hello World" every time it is accessed via a web
browser.

Example 2-1. A servlet that prints "Hello World"

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();

out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
This servlet extends the HttpServlet class and overrides the doGet() method inherited
from it. Each time the web server receives a GET request for this servlet, the server invokes
this doGet() method, passing it an HttpServletRequest object and an
HttpServletResponse object.

The HttpServletRequest represents the client's request. This object gives a servlet access
to information about the client, the parameters for this request, the HTTP headers passed
along with the request, and so forth.

© Aptech Ltd Version 1.0 21 of 194


Web Component Development Using Java References

The HttpServletResponse represents the servlet's response. A servlet can use this object
to return data to the client. This data can be of any content type, though the type should be
specified as part of the response. A servlet can also use this object to set HTTP response
headers.

Our servlet first uses the setContentType() method of the response object to set the
content type of its response to "text/html", the standard MIME content type for HTML
pages. Then, it uses the getWriter() method to retrieve a PrintWriter, the international-
friendly counterpart to a PrintStream. PrintWriter converts Java's Unicode characters to
a locale-specific encoding. For an English locale, it behaves same as a PrintStream. Finally,
the servlet uses this PrintWriter to send its "Hello World" HTML to the client.

That's it! That's all the code needed to say hello to everyone who "surfs" to our servlet.

2.3.2. Running Hello World

When developing servlets you need two things: the Servlet API class files, which are used
for compiling, and a servlet engine such as a web server, which is used for deployment. To
obtain the Servlet API class files, you have several options:

 Install the Java Servlet Development Kit (JSDK), available for free at
http://java.sun.com/products/servlet/. JSDK Version 2.0 contains the class files for
the Servlet API 2.0, along with their source code and a simple web server that acts
as a servlet engine for HTTP servlets. It works with JDK 1.1 and later. (Note that the
JSDK is the Servlet API reference implementation, and as such its version number
determines the Servlet API version number.)

 Install one of the many full-featured servlet engines, each of which typically bundles
the Servlet API class files.

Why not use the servlet engine included in JSDK 2.0? Because that servlet engine is bare-
bones simple. It implements the Servlet API 2.0 and nothing more. Features like robust
session tracking, server-side includes, servlet chaining, and JavaServer Pages have been
left out because they are technically not part of the Servlet API. For these features, you
need to use a full-fledged servlet engine like the Java Web Server or one of its competitors.

So, what do we do with our code to make it run in a web server? Well, it depends on your
web server. The examples in this book use Sun's Java Web Server 1.1.1, unofficially
considered the reference implementation for how a web server should support servlets. It's
free for educational use and has a 30-day trial period for all other use. You can download a
copy from http://java.sun.com/products. The Java Web Server includes plenty of
documentation explaining the use of the server, so while we discuss the general concepts
involved with managing the server, we're leaving the details to Sun's documentation. If you
choose to use another web server, these examples should work for you, but we cannot
make any guarantees.

If you are using the Java Web Server, you should put the source code for the servlet in the
server_root/servlets directory (where server_root is the directory where you installed
your server). This is the standard location for servlet class files. Once you have the "Hello
World" source code in the right location, you need to compile it. The standard javac
compiler (or your favorite graphical Java development environment) can do the job. Just be
sure you have the javax.servlet and javax.servlet.http packages in your classpath.

© Aptech Ltd Version 1.0 22 of 194


Web Component Development Using Java References

With the Java Web Server, all you have to do is include server_root/lib/jws.jar (or a future
equivalent) somewhere in your classpath.

Now that you have your first servlet compiled, there is nothing more to do but start your
server and access the servlet! Starting the server is easy. Look for the httpd script (or
httpd.exe program under Windows) in the server_root/bin directory. This should start your
server if you're running under Solaris or Windows. On other operating systems, or if you
want to use your own Java Runtime Environment (JRE), you'll need to use httpd.nojre. In
the default configuration, the server listens on port 8080.

There are several ways to access a servlet. For this example, we'll do it by explicitly
accessing a URL with /servlet/ prepended to the servlet's class name.[2] You can enter this
URL in your favorite browser: http://server:8080/servlet/HelloWorld. Replace server with
the name of your server machine or with localhost if the server is on your local machine.
You should see a page similar to the one shown in Figure 2-3.

[2] Beware, servlets are placed in a servlets (plural) directory but are invoked with a
servlet(singular) tag. If you think about it, this makes a certain amount of sense, as servlets
go in the servlets directory while a single servlet is referenced with the servlet tag.

Figure 2-3. The Hello World servlet

If the servlet were part of a package, it would need to be placed in


server_root/servlets/package/name and referred to with the URL
http://server:8080/servlet/package.name.HelloWorld.

An alternate way to refer to a servlet is by its registered name. This does not have to be the
same as its class name, although it can be. With the Java Web Server, you register servlets
via the JavaServer Administration Tool, an administration applet that manages the server,
usually available at http://server:9090/. Choose to manage the Web Service, go to the
Servlets section, and then Add a new servlet. Here you can specify the name of the new
servlet and the class associated with that name (on some servers the class can be an HTTP
URL from which the servlet class file will be automatically loaded). If we choose the name
"hi" for our HelloWorld servlet, we can then access it at the URL
http://server:8080/servlet/hi.

A third way to access a servlet is through a servlet alias. The URL of a servlet alias looks like
any other URL. The only difference is that the server has been told that the URL should be
handled by a particular servlet. For example, we can choose to have
http://server:8080/hello.html invoke the HelloWorld servlet. Using aliases in this way can
help hide a site's use of servlets; it lets a servlet seamlessly replace an existing page at any
given URL. To create a servlet alias, choose to manage the Web Service, go to the Setup
section, choose Servlet Aliases, and then Add the alias.

© Aptech Ltd Version 1.0 23 of 194


Web Component Development Using Java References

2.3.3. Handling Form Data

The "Hello World" servlet is not very exciting, so let's try something slightly more ambitious.
This time we'll create a servlet that greets the user by name. It's not hard. First, we need
an HTML form that asks the user for his or her name. The following page should suffice:

<HTML>
<HEAD>
<TITLE>Introductions</TITLE>
</HEAD>
<BODY>
<FORM METHOD=GET ACTION="/servlet/Hello">
If you don't mind me asking, what is your name?
<INPUT TYPE=TEXT NAME="name"><P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

Figure 2-4 shows how this page appears to the user.

Figure 2-4. An HTML form

When the user submits this form, his name is sent to the Hello servlet because we've set
the ACTION attribute to point to the servlet. The form is using the GET method, so any data
is appended to the request URL as a query string. For example, if the user enters the name
"Inigo Montoya," the request URL is
http://server:8080/servlet/Hello?name=Inigo+Montoya. The space in the name is
specially encoded as a plus sign by the browser because URLs cannot contain spaces.

A servlet's HttpServletRequest object gives it access to the form data in its query string.
Example 2-2 shows a modified version of our Hello servlet that uses its request object to
read the "name" parameter.

Example 2-2. A servlet that knows to whom it's saying hello

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Hello extends HttpServlet {

© Aptech Ltd Version 1.0 24 of 194


Web Component Development Using Java References

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();

String name = req.getParameter("name");


out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}

public String getServletInfo() {


return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
This servlet is nearly identical to the HelloWorld servlet. The most important change is that
it now calls req.getParameter("name") to find out the name of the user and that it then
prints this name instead of the harshly impersonal (not to mention overly broad) "World".
The getParameter() method gives a servlet access to the parameters in its query string. It
returns the parameter's decoded value or null if the parameter was not specified. If the
parameter was sent but without a value, as in the case of an empty form field,
getParameter() returns the empty string.

This servlet also adds a getServletInfo() method. A servlet can override this method to
return descriptive information about itself, such as its purpose, author, version, and/or
copyright. It's akin to an applet's getAppletInfo(). The method is used primarily for
putting explanatory information into a web server administration tool. You'll notice we won't
bother to include it in future examples because it is clutter for learning.

The servlet's output looks something like what is shown in Figure 2-5.

Figure 2-5. The Hello servlet using form data

2.3.4. Handling POST Requests

You've now seen two servlets that implement the doGet() method. Now let's change our
Hello servlet so that it can handle POST requests as well. Because we want the same
behavior with POST as we had for GET, we can simply dispatch all POST requests to the
doGet() method with the following code:

© Aptech Ltd Version 1.0 25 of 194


Web Component Development Using Java References

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
doGet(req, res);
}
Now the Hello servlet can handle form submissions that use the POST method:

<FORM METHOD=POST ACTION="/servlet/Hello">


In general, it is best if a servlet implements either doGet() or doPost(). Deciding which to
implement depends on what sort of requests the servlet needs to be able to handle, as
discussed earlier. The code you write to implement the methods is almost identical. The
major difference is that doPost() has the added ability to accept large amounts of input.

You may be wondering what would have happened had the Hello servlet been accessed with
a POST request before we implemented doPost(). The default behavior inherited from
HttpServlet for both doGet() and doPost() is to return an error to the client saying the
requested URL does not support that method.

2.3.5. Handling HEAD Requests

A bit of under-the-covers magic makes it trivial to handle HEAD requests (sent by a client
when it wants to see only the headers of the response). There is no doHead() method to
write. Any servlet that subclasses HttpServlet and implements the doGet() method
automatically supports HEAD requests.

Here's how it works. The service() method of the HttpServlet identifies HEAD requests and
treats them specially. It constructs a modified HttpServletResponse object and passes it,
along with an unchanged request, to the doGet() method. The doGet() method proceeds as
normal, but only the headers it sets are returned to the client. The special response object
effectively suppresses all body output.[3]Figure 2-6 shows how an HTTP servlet handles
HEAD requests.

[3] Jason is proud to report that Sun added this feature in response to comments he made
during beta testing.

Figure 2-6. An HTTP servlet handling a HEAD request

Although this strategy is convenient, you can sometimes improve performance by detecting
HEAD requests in the doGet() method, so that it can return early, before wasting cycles
writing output that no one will see. Example 2-3 uses the request's getMethod() method to
implement this strategy (more properly called a hack) in our Hello servlet.

© Aptech Ltd Version 1.0 26 of 194


Web Component Development Using Java References

Example 2-3. The Hello servlet modified to return quickly in response to HEAD
requests

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Hello extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

// Set the Content-Type header


res.setContentType("text/html");

// Return early if this is a HEAD


if (req.getMethod().equals("HEAD")) return;

// Proceed otherwise
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
}
Notice that we set the Content-Type header, even if we are dealing with a HEAD request.
Headers such as these are returned to the client. Some header values, such as Content-
Length, may not be available until the response has already been calculated. If you want to
be accurate in returning these header values, the effectiveness of this shortcut is limited.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 27 of 194


Web Component Development Using Java References

Introduction to Request Dispatcher


Source http://www.studytonight.com/servlet/request-dispatcher.php

Date of 02/04/2015
Retrieval:

RequestDispatcher is an interface, implementation of which defines an object which can


dispatch request to any resources(such as HTML, Image, JSP, Servlet) on the server.

Methods of RequestDispatcher

RequestDispatcher interface provides two important methods

Methods Description

void forward(ServletRequest request, forwards a request from a servlet to another


ServletResponse response) resource (servlet, JSP file, or HTML file) on the
server

void include(ServletRequest request, includes the content of a resource (servlet, JSP


ServletResponse response) page, HTML file) in the response

How to get an Object of RequestDispatcher

getRequestDispatcher() method of ServletRequest returns the object

of RequestDispatcher.

RequestDispatcher rs = request.getRequestDispatcher("hello.html");

rs.forward(request,response);

© Aptech Ltd Version 1.0 28 of 194


Web Component Development Using Java References

OR

RequestDispatcher rs = request.getRequestDispatcher("hello.html");

rs.include(request,response);

Example demonstrating usage of RequestDispatcher

In this example, we will show you how RequestDispatcher is used


to forward or include response of a resource in a Servlet. Here we are
using index.html to get username and password from the user, Validate Servlet will
validate the password entered by the user, if the user has entered "studytonight" as
password, then he will be forwarded to Welcome Servlet else the user will stay on the
index.html page and an error message will be displayed.

© Aptech Ltd Version 1.0 29 of 194


Web Component Development Using Java References

Files to be created :

 index.html will have form fields to get user information.

 Validate.java will validate the data entered by the user.

 Welcome.java will be the welcome page.

 web.xml , the deployment descriptor.

index.html

<form method="post" action="Validate">

Name:<input type="text" name="user" /><br/>

Password:<input type="password" name="pass" ><br/>

<input type="submit" value="submit">

</form>

Validate.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Validate extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

String name = request.getParameter("user");

String password = request.getParameter("pass");

if(password.equals("studytonight"))

© Aptech Ltd Version 1.0 30 of 194


Web Component Development Using Java References

RequestDispatcher rd = request.getRequestDispatcher("Welcome");

rd.forward(request, response);

else

out.println("<font color='red'><b>You have entered incorrect


password</b></font>");

RequestDispatcher rd =
request.getRequestDispatcher("index.html");

rd.include(request, response);

}finally {

out.close();

Welcome.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Welcome extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

© Aptech Ltd Version 1.0 31 of 194


Web Component Development Using Java References

out.println("<h2>Welcome user</h2>");

} finally {

out.close();

web.xml

<web-app>

<servlet>

<servlet-name>Validate</servlet-name>

<servlet-class>Validate</servlet-class>

</servlet>

<servlet>

<servlet-name>Welcome</servlet-name>

<servlet-class>Welcome</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Validate</servlet-name>

<url-pattern>/Validate</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Welcome</servlet-name>

<url-pattern>/Welcome</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

</web-app>

© Aptech Ltd Version 1.0 32 of 194


Web Component Development Using Java References

This will be the first screen. You can enter your Username and Password here.

When you click on Submit, Password will be validated, if it is not 'studytonight' , error
message will be displayed.

Enter any Username, but enter 'studytonight' as password.

© Aptech Ltd Version 1.0 33 of 194


Web Component Development Using Java References

Password will be successfully validated and you will be directed to the Welcome Servlet.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 34 of 194


Web Component Development Using Java References

Session 3: Session Tracking

Session Tracking

Source http://users.polytech.unice.fr/~buffa/cours/internet/POLYS/servlets/Servlet-
Tutorial-Session-Tracking.html#Section4

Date of 02/04/2015
Retrieval:

There are a number of problems that arise from the fact that HTTP is a "stateless" protocol.
In particular, when you are doing on-line shopping, it is a real annoyance that the Web
server can't easily remember previous transactions. This makes applications like shopping
carts very problematic: when you add an entry to your cart, how does the server know
what's already in your cart? Even if servers did retain contextual information, you'd still
have problems with e-commerce. When you move from the page where you specify what
you want to buy (hosted on the regular Web server) to the page that takes your credit card
number and shipping address (hosted on the secure server that uses SSL), how does the
server remember what you were buying?

There are three typical solutions to this problem.

1. Cookies. You can use HTTP cookies to store information about a shopping session,
and each subsequent connection can look up the current session and then extract
information about that session from some location on the server machine. This is an
excellent alternative, and is the most widely used approach. However, even though
servlets have a high-level and easy-to-use interface to cookies, there are still a
number of relatively tedious details that need to be handled:

 Extracting the cookie that stores the session identifier from the other cookies
(there may be many, after all),

 Setting an appropriate expiration time for the cookie (sessions interrupted by 24


hours probably should be reset), and

 Associating information on the server with the session identifier (there may be far
too much information to actually store it in the cookie, plus sensitive data like
credit card numbers should never go in cookies).

© Aptech Ltd Version 1.0 35 of 194


Web Component Development Using Java References

2. URL Rewriting. You can append some extra data on the end of each URL that
identifies the session, and the server can associate that session identifier with data it
has stored about that session. This is also an excellent solution, and even has the
advantage that it works with browsers that don't support cookies or where the user
has disabled cookies. However, it has most of the same problems as cookies, namely
that the server-side program has a lot of straightforward but tedious processing to
do. In addition, you have to be very careful that every URL returned to the user
(even via indirect means like Location fields in server redirects) has the extra
information appended. And, if the user leaves the session and comes back via a
bookmark or link, the session information can be lost.

3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is
submitted, the specified name and value are included in the GET or POST data. This
can be used to store information about the session. However, it has the major
disadvantage that it only works if every page is dynamically generated, since the
whole point is that each session has a unique identifier.

Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level
interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies
if the browser supports them, but automatically revert to URL-rewriting when cookies are
unsupported or explicitly disabled. But the servlet author doesn't need to bother with many
of the details, doesn't have to explicitly manipulate cookies or information appended to the
URL, and is automatically given a convenient place to store data that is associated with each
session.

2. The Session Tracking API

Using sessions in servlets is quite straightforward, and involves looking up the session
object associated with the current request, creating a new session object when necessary,
looking up information associated with a session, storing information in a session, and
discarding completed or abandoned sessions.

2.1 Looking up the HttpSession object associated with the current request.

This is done by calling the getSession method of HttpServletRequest. If this returns null,
you can create a new session, but this is so commonly done that there is an option to
automatically create a new session if there isn't one already.

Just pass true to getSession. Thus, your first step usually looks like this:

© Aptech Ltd Version 1.0 36 of 194


Web Component Development Using Java References

HttpSession session = request.getSession(true);

2.2 Looking up Information Associated with a Session.

HttpSession objects live on the server; they're just automatically associated with the
requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session
objects have a builtin data structure that let you store any number of keys and associated
values. In version 2.1 and earlier of the servlet API, you use getValue("key") to look up a
previously stored value. The return type is Object, so you have to do a typecast to whatever
more specific type of data was associated with that key in the session. The return value is
null if there is no such attribute. In version 2.2, getValue is deprecated in favor of
getAttribute, both because of the better naming match with setAttribute (the match for
getValue is putValue, not setValue), and because setAttribute lets you use an attached
HttpSessionBindingListener to monitor values, while putValue doesn't. Nevertheless,
since few commercial servlet engines yet support version 2.2, I'll use getValue in my
examples.

Here's one representative example, assuming ShoppingCart is some class you've defined
yourself that stores information on items being purchased.
HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}

In most cases, you have a specific attribute name in mind, and want to find the value (if
any) already associated with it. However, you can also discover all the attribute names in a
given session by calling getValueNames, which returns a String array. In version 2.2, use
getAttributeNames, which has a better name and which is more consistent in that it
returns an Enumeration, just like the getHeaders and getParameterNames methods of
HttpServletRequest.

Although the data that was explicitly associated with a session is the part you care most
about, there are some other pieces of information that are sometimes useful as well.

© Aptech Ltd Version 1.0 37 of 194


Web Component Development Using Java References

 getId. This method returns the unique identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session, or when logging information about previous sessions.

 isNew. This returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client
request. It returns false for preexisting sessions.

 getCreationTime. This returns the time, in milliseconds since the epoch, at which
the session was made. To get a value useful for printing out, pass the value to the
Date constructor or the setTimeInMillis method of GregorianCalendar.

 getLastAccessedTime. This returns the time, in milliseconds since the epoch, at


which the session was last sent from the client.
 getMaxInactiveInterval. This returns the amount of time, in seconds, that a
session should go without access before being automatically invalidated. A negative
value indicates that the session should never timeout.

2.3 Associating Information with a Session

As discussed in the previous section, you read information associated with a session by
using getValue (or getAttribute in version 2.2 of the servlet spec). To specify information,
you use putValue (or setAttribute in version 2.2), supplying a key and a value. Note that
putValue replaces any previous values. Sometimes that's what you want (as with the
referringPage entry in the example below), but other times you want to retrieve a previous
value and augment it (as with the previousItems entry below). Here's an example:
HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));
// You still have to do putValue, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.putValue("previousItems", previousItems);

3. Example: Showing Session Information

© Aptech Ltd Version 1.0 38 of 194


Web Component Development Using Java References

Here is a simple example that generates a Web page showing some information about the
current session. You can also download the source or try it on-line.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

/** Simple example of session tracking. See the shopping


* cart example for a more detailed one.
* <P>
* Part of tutorial on servlets and JSP that appears at
* http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
* 1999 Marty Hall; may be freely used or adapted.
*/

public class ShowSession extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Searching the Web";
String heading;
Integer accessCount = new Integer(0);;
if (session.isNew()) {
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
Integer oldAccessCount =
// Use getAttribute, not getValue, in version
// 2.2 of servlet API.

© Aptech Ltd Version 1.0 39 of 194


Web Component Development Using Java References

(Integer)session.getValue("accessCount");
if (oldAccessCount != null) {
accessCount =
new Integer(oldAccessCount.intValue() + 1);
}
}
// Use putAttribute in version 2.2 of servlet API.
session.putValue("accessCount", accessCount);

out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +
" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +
"</TABLE>\n" +
"</BODY></HTML>");

public void doPost(HttpServletRequest request,

© Aptech Ltd Version 1.0 40 of 194


Web Component Development Using Java References

HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Here's a typical result, shown after visiting the page several without quitting the browser in
between:

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 41 of 194


Web Component Development Using Java References

New Session Management Features in Servlet 3.0

Source https://madhuraoakblog.wordpress.com/2014/05/16/new-session-
management-features-in-servlet-3-0/

Date of 02/04/2015
Retrieval:

The three mechanisms of client-side session management are HTTP Cookies, URL rewritting
and HTML hidden form fields. Servlet 3.0 provides following new features in session
management.

Session tracking cookie name

The session tracking HTTP cookie should be named as JSESSIONID by all Servlet 3.0
compliant servlet containers. Some servlet containers such as Tomcat may allow
customizing this name. This cookie stores the session id on the client browser which is
returned to the server on every request made to the server during the session life-time.

HttpOnly Cookies

HttpOnly cookies cannot be accessed from client-side scripting code provided the browsers
support the HttpOnly flag. Some Cross-Site Scripting (XSS) attacks are mitigated by
HttpOnly cookies. The malicious scripts injected in trusted websites cannot read and modify
the HttpOnly cookies and thus the sensitive information stored in HTTP cookies can be
protected from theft and misuse.

Servlet 3.0 API allows creation of HttpOnly cookies by providing setHttpOnly() method on
Cookie class. HttpOnly cookies can also be configured in web.xml as follows:

<session-config>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
</session-config>

Sending HTTP cookies only on SSL

The communication between client and server on Server Socket Layer (SSL) is done over a
secured connection. The data transmitted between server and client on SSL is always
encrypted. SSL provides two-way encryption. HTTP cookies can be configured to be
transmitted only on SSL in Servlet 3.0 by using the following configuration in web.xml. This
enables encryption of cookies. The SSL should be enabled on the web server to use this
feature.

© Aptech Ltd Version 1.0 42 of 194


Web Component Development Using Java References

<session-config>
<cookie-config>
<secure>true</secure>
</cookie-config>
</session-config>

Configure session tracking mechanism

The session tracking mechanism can be defined in web.xml using <tracking-mode> in


Servlet 3.0. Its values can be COOKIE, URL or SSL. The JSESSIONID HTTP cookie is created
when the tracking mode is set as COOKIE. The session Id is passed as a URL parameter
when the tracking mode is URL. The name of URL parameter is jsessionid. If the session
tracking cookie name is customized, the same name will be used as session id parameter
name in URL. The session id can be passed on SSL using tracking mode as SSL.

<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 43 of 194


Web Component Development Using Java References

Session 4: Filters and Annotations

Filtering Requests and Responses

Source http://docs.oracle.com/javaee/6/tutorial/doc/bnagb.html

Date of 24/07/2014
Retrieval:

A filter is an object that can transform the header and content (or both) of a request or
response. Filters differ from web components in that filters usually do not themselves create
a response. Instead, a filter provides functionality that can be “attached” to any kind of web
resource. Consequently, a filter should not have any dependencies on a web resource for
which it is acting as a filter; this way, it can be composed with more than one type of web
resource.

The main tasks that a filter can perform are as follows:

 Query the request and act accordingly.


 Block the request-and-response pair from passing any further.
 Modify the request headers and data. You do this by providing a customized version
of the request.
 Modify the response headers and data. You do this by providing a customized version
of the response.
 Interact with external resources.

Applications of filters include authentication, logging, image conversion, data compression,


encryption, tokenizing streams, XML transformations, and so on.

You can configure a web resource to be filtered by a chain of zero, one, or more filters in a
specific order. This chain is specified when the web application containing the component is
deployed and is instantiated when a web container loads the component.

Programming Filters

The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the
javax.servlet package. You define a filter by implementing the Filter interface.

Use the @WebFilter annotation to define a filter in a web application. This annotation is
specified on a class and contains metadata about the filter being declared. The annotated
filter must specify at least one URL pattern. This is done by using the urlPatterns or value
attribute on the annotation. All other attributes are optional, with default settings. Use the
value attribute when the only attribute on the annotation is the URL pattern; use the
urlPatterns attribute when other attributes are also used.

Classes annotated with the @WebFilter annotation must implement the javax.servlet.Filter
interface.

© Aptech Ltd Version 1.0 44 of 194


Web Component Development Using Java References

To add configuration data to the filter, specify the initParams attribute of the @WebFilter
annotation. The initParams attribute contains a @WebInitParam annotation. The following
code snippet defines a filter, specifying an initialization parameter:

import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(filterName = "TimeOfDayFilter",
urlPatterns = {"/*"},
initParams = {
@WebInitParam(name = "mood", value = "awake")})
public class TimeOfDayFilter implements Filter {
....

The most important method in the Filter interface is doFilter, which is passed request,
response, and filter chain objects. This method can perform the following actions:

 Examine the request headers.


 Customize the request object if the filter wishes to modify request headers or data.
 Customize the response object if the filter wishes to modify response headers or
data.
 Invoke the next entity in the filter chain. If the current filter is the last filter in the
chain that ends with the target web component or static resource, the next entity is
the resource at the end of the chain; otherwise, it is the next filter that was
configured in the WAR. The filter invokes the next entity by calling the doFilter
method on the chain object, passing in the request and response it was called with
or the wrapped versions it may have created. Alternatively, the filter can choose to
block the request by not making the call to invoke the next entity. In the latter case,
the filter is responsible for filling out the response.
 Examine response headers after invoking the next filter in the chain.
 Throw an exception to indicate an error in processing.

In addition to doFilter, you must implement the init and destroy methods. The init method
is called by the container when the filter is instantiated. If you wish to pass initialization
parameters to the filter, you retrieve them from the FilterConfig object passed to init.

Programming Customized Requests and Responses

There are many ways for a filter to modify a request or a response. For example, a filter can
add an attribute to the request or can insert data in the response.

A filter that modifies a response must usually capture the response before it is returned to
the client. To do this, you pass a stand-in stream to the servlet that generates the
response. The stand-in stream prevents the servlet from closing the original response
stream when it completes and allows the filter to modify the servlet’s response.

To pass this stand-in stream to the servlet, the filter creates a response wrapper that
overrides the getWriter or getOutputStream method to return this stand-in stream. The

© Aptech Ltd Version 1.0 45 of 194


Web Component Development Using Java References

wrapper is passed to the doFilter method of the filter chain. Wrapper methods default to
calling through to the wrapped request or response object.

To override request methods, you wrap the request in an object that extends either
ServletRequestWrapper or HttpServletRequestWrapper. To override response methods,
you wrap the response in an object that extends either ServletResponseWrapper or
HttpServletResponseWrapper.

Specifying Filter Mappings

A web container uses filter mappings to decide how to apply filters to web resources. A filter
mapping matches a filter to a web component by name or to web resources by URL pattern.
The filters are invoked in the order in which filter mappings appear in the filter mapping list
of a WAR. You specify a filter mapping list for a WAR in its deployment descriptor by either
using NetBeans IDE or coding the list by hand with XML.

If you want to log every request to a web application, you map the hit counter filter to the
URL pattern /*.

You can map a filter to one or more web resources, and you can map more than one filter to
a web resource. This is illustrated in Figure 15-1, where filter F1 is mapped to servlets S1,
S2, and S3; filter F2 is mapped to servlet S2; and filter F3 is mapped to servlets S1 and S2.

Figure 15-1 Filter-to-Servlet Mapping

Recall that a filter chain is one of the objects passed to the doFilter method of a filter. This
chain is formed indirectly by means of filter mappings. The order of the filters in the chain is
the same as the order in which filter mappings appear in the web application deployment
descriptor.

When a filter is mapped to servlet S1, the web container invokes the doFilter method of F1.
The doFilter method of each filter in S1’s filter chain is invoked by the preceding filter in the
chain by means of the chain.doFilter method. Because S1’s filter chain contains filters F1
and F3, F1’s call to chain.doFilter invokes the doFilter method of filter F3. When F3’s doFilter
method completes, control returns to F1’s doFilter method.

© Aptech Ltd Version 1.0 46 of 194


Web Component Development Using Java References

To Specify Filter Mappings Using NetBeans IDE

1. Expand the application’s project node in the Project pane.


2. Expand the Web Pages and WEB-INF nodes under the project node.
3. Double-click web.xml.
4. Click Filters at the top of the editor pane.
5. Expand the Servlet Filters node in the editor pane.
6. Click Add Filter Element to map the filter to a web resource by name or by URL pattern.
7. In the Add Servlet Filter dialog, enter the name of the filter in the Filter Name field.
8. Click Browse to locate the servlet class to which the filter applies.

You can include wildcard characters so that you can apply the filter to more than one
servlet.

9. Click OK.
10. To constrain how the filter is applied to requests, follow these steps.

a. Expand the Filter Mappings node.


b. Select the filter from the list of filters.
c. Click Add.
d. In the Add Filter Mapping dialog, select one of the following dispatcher types:

 REQUEST: Only when the request comes directly from the client
 ASYNC: Only when the asynchronous request comes from the client
 FORWARD: Only when the request has been forwarded to a component
 INCLUDE: Only when the request is being processed by a component that has
been included
 ERROR: Only when the request is being processed with the error page
mechanism

You can direct the filter to be applied to any combination of the preceding situations by
selecting multiple dispatcher types. If no types are specified, the default option is REQUEST.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 47 of 194


Web Component Development Using Java References

How to upload file Using JSP/Ser vlet?

Source http://www.javaquery.com/2011/12/how-to-upload-file-using-jsp-servlet.html

Date of 02/04/2015
Retrieval:

Uploading Files
Technology world moving fast as a speed of light. Its getting change day by day. Web
application is build under the MVC (Model-View-Controller) model. Colleges still using servlet
in study. In below article we'll discuss how you can manage your web application to upload
files.

Required .jar files

 commons-io-2.0.jar ( http://commons.apache.org/io/download_io.cgi )
 commons-fileupload-1.2.2.jar
( http://commons.apache.org/fileupload/download_fileupload.cgi )

import bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

All above packages you have to import in you servlet. Below code is for file upload in
servlet. File upload directory is "/upload/"

List fileItemsList = null;


float filesize = 0;

© Aptech Ltd Version 1.0 48 of 194


Web Component Development Using Java References

String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/upload/");

//Change upload with your directory


HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(new
DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(FileUploadExample.class.getName()).log(Level.SEVERE,
null, ex);
//Change above line replace FileUploadExample with your file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}

/*
* If you want to pass some other data from JSP page. You can
access then in this way.
* For each field you have do create if like below.
* if (fileItemTemp.getFieldName().equals("Name of other field
like:Firstname")) {
* String Firstname = fileItemTemp.getString();
* }
*/

} else {
fileItem = fileItemTemp;
}
}

if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;

© Aptech Ltd Version 1.0 49 of 194


Web Component Development Using Java References

//If you want to limit the file size. Here 30MB file size is
allowed you can change it
if (filesize > 30.0) {
//Pass error message in session.
setNotification _sN = new setNotification();
_sN.setError("File size can't be more than 30MB");
session.setAttribute("error", _sN);
} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../upload/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),
fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("error", _sN);
}
}
}
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
Now notification class to shows the message to users. Use the below code.

public class setNotification {


private String Error="";
public String getError() {
return Error;
}
public void setError(String Error) {

© Aptech Ltd Version 1.0 50 of 194


Web Component Development Using Java References

this.Error = Error;
}
}
The JSP file. Change the servlet name in action (form). Change package import
bean.setNotification.

<%@page import="bean.setNotification"%>
<%
setNotification _sN = new setNotification();
if (session.getAttribute("error") != null) {
_sN = (setNotification) session.getAttribute("error");
}

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example</title>
<link type="text/css" href="css/bundle.css" rel="StyleSheet"/>
</head>
<body>
<center>
<div class="signal_box" style="width: 400px;height: 150px">
<div class="head">File Upload - javaQuery.com</div>
<form action="FileUploadExample" method="post"
enctype="multipart/form-data">
<input type="file" name="myFile"/><br/>
<input type="submit" value="Upload it"/>
</form>
<br/>
<%=_sN.getError()%>
<%_sN.setError("");%>
</div>
</center>
</body>
</html>

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 51 of 194


Web Component Development Using Java References

Session 5: Database Access and Event Handling

Ser vlet Event Listeners

Source http://www.informit.com/articles/article.aspx?p=170963&seqNum=7

Date of 02/04/2015
Retrieval:

Servlet Event Listeners

In many situations it is desirable to be notified of container-managed life cycle events. An


easy example to think of is knowing when the container initializes a Web Application and
when a Web Application is removed from use. Knowing this information is helpful because
you may have code that relies on it, perhaps a database that needs to be loaded at startup
and saved at shutdown. Another good example is keeping track of the number of concurrent
clients using a Web Application. This functionality can be done with what you currently know
of Servlets; however, it can much more easily be done using a listener that waits for a client
to start a new session. The greater point being presented here is that a container can be
used to notify a Web Application of important events, and Servlet event listeners are the
mechanism.

All of the Servlet event listeners are defined by interfaces. There are event listener
interfaces for all of the important events related to a Web Application and Servlets. In order
to be notified of events, a custom class, which implements the correct listener interface,
needs to be coded and the listener class needs to be deployed via web.xml. All of the
Servlet event listeners will be mentioned now; however, a few of the event listeners will not
make complete sense until the later chapters of the book. In general, all of the event
listeners work the same way so this fact is fine as long as at least one good example is
provided here.

The interfaces for event listeners correspond to request life cycle events, request attribute
binding, Web Application life cycle events, Web Application attribute binding, session 36 life
cycle events, session attribute binding, and session serialization, and appear, respectively,
as follows:

 javax.servlet.ServletRequestListener
 javax.servlet.ServletRequestAttributeListener
 javax.servlet.ServletContextListener
 javax.servlet.ServletContextAttributeListener
 javax.servlet.http.HttpSessionListener
 javax.servlet.http.HttpSessionAttributeListener
 javax.servlet.http.HttpSessionAttributeListener

Use of each listener is intuitive given an implementation of one and an example deployment
descriptor. All of the listener interfaces define events for either the creation and destruction
of an object or for notification of the binding or unbinding of an object to a particular scope.

© Aptech Ltd Version 1.0 52 of 194


Web Component Development Using Java References

As an example, let us create a listener that tracks the number of concurrent users. We could
create a simple hit counter, by tracking how many requests are created; however, the
previous hit counter examples in this chapter do a fine job providing the same functionality.
Tracking the number of concurrent users is something that we have yet to see, and allows
the introduction of session scope. For now, think of sessions as being created only once per
unique client—regardless if the same person visits the site more than once. This is different
from requests, which are created every time a client requests a resource. The listener
interface we are going to implement is HttpSessionListener. It provides notification of two
events: session creation and session destruction. In order to keep track of concurrent users,
we will keep a static count variable that will increase incrementally when a session is
created and decrease when a session is destroyed.

The physical methods required by the HttpSessionListener interface are as follows:

 void sessionCreated(HttpSessionEvent evt): The method invoked when a


session is created by the container. This method will almost always be invoked only
once per a unique client.

 void sessionDestroyed(HttpSessionEvent evt): The method invoked when a


session is destroyed by the container. This method will be invoked when a unique
client's session times out—that is, after they fail to revisit the Web site for a given
period of time, usually 15 minutes.

Listing 2-20 provides our listener class's code, implementing the preceding two methods.
Save the code as ConcurrentUserTracker.java in the /WEB-INF/classes/com/jspbook
directory of the jspbook Web Application.

Listing 2-20. ConcurrentUserTracker.java

package com.jspbook;
import javax.servlet.*;
import javax.servlet.http.*;
public class ConcurrentUserTracker implements HttpSessionListener {
static int users = 0;

public void sessionCreated(HttpSessionEvent e) {


users++;
}
public void sessionDestroyed(HttpSessionEvent e) {
users--;
}
public static int getConcurrentUsers() {
return users;
}
}

© Aptech Ltd Version 1.0 53 of 194


Web Component Development Using Java References

The listener's methods are intuitive and the logic is simple. The class is trivial to create
because the container is managing all the hard parts: handling HTTP requests, trying to
keep a session, and keeping a timer in order to successfully time-out unused sessions.

Deploy the listener by adding the entry in Listing 2-21 to web.xml. Add the entry after the
starting webapp element but before any Servlet deployments.

Listing 2-21. Deployment of the Concurrent User Listener

<listener>
<listener-class>
com.jspbook.ConcurrentUserTracker
</listener-class>
</listener>

Notice that the deployment does not specify what type of listener interface is being used.
This type of information is not needed because the container can figure it out; therefore,
deployment of all the different listeners is similar to the above code. Create a listener
element with a child listener-class element that has the name of the listener class.

One more addition is required before the concurrent user example can be tested. The
concurrent user tracker currently doesn't output information about concurrent users! Let us
create a Servlet that uses the static getConcurrentUsers() method to display the number of
concurrent users. Save the code in Listing 2-22 as DisplayUsers.java in the /WEB-
INF/com/jspbook directory of the jspbook Web Application.

Listing 2-22. DisplayUsers.java

package com.jspbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayUsers extends HttpServlet {


public void doGet(HttpServletRequest request,

HttpServletResponse response)
throws IOException, ServletException {

request.getSession();

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("Users:");
out.print(ConcurrentUserTracker.getConcurrentUsers());
out.println("</html>");
}
}

© Aptech Ltd Version 1.0 54 of 194


Web Component Development Using Java References

Deploy the Servlet to the /DisplayUsers URL mapping. Compile both


ConcurrentUserTracker.java and DisplayUser.java and reload the jspbook Web Application
for the changes to take effect. Test the new functionality out by browsing to
http://127.0.0.1/jspbook/DisplayUsers. An HTML page appears describing how many users
are currently using the Web Application. A browser rendering would be provided; however,
the page literally displays nothing more than the text "Users:" followed by the number of
current users.

When browsing to the Servlet, it should say one user is currently using the Web Application.
If you refresh the page, it will still say only one user is using the Web Application. Try
opening a second Web browser and you should see that the page states two people are
using the Web Application. Upon closing your Web browser, the counter will not go down,
but after not visiting the Web Application for 15 minutes, it will. You can test this out by
opening two browsers (to create two concurrent users) and only using one of the browsers
for the next 15 minutes. Eventually, the unused browser's session will time-out and the Web
Application will report only one concurrent user. In real-world use, odds are that several
independent people will be using a Web Application at any given time. In this situation you
don't need to do anything but visit the DisplayUsers Servlet to see the current amount of
concurrent users.

The concurrent user tracker is a handy piece of code; however, the greater point to realize
is how Servlet event listeners can be coded and deployed for use. Event listeners in general
are intuitive to use; the hard part is figuring out when and how they are best used, which is
hard to fully explain in this chapter. In later chapters of the book, event listeners will be
used to solve various problems and complement code. Keep an eye out for them.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 55 of 194


Web Component Development Using Java References

Session 6: Asynchronous Servlets and Clients

Asynchronous Ser vlet – A new feature in Ser vlet 3.0 and


Java EE 6

Source http://www.javabeat.net/asynchronous-servlet-servlet-3-0/
Date of 02/04/2015
Retrieval:

When Java EE 6 was announced with a new servlet specification i.e Servlet 3.0 –
Asynchronous servlet was a very important feature added to the new specification. Suppose
your servlet does a long running task like making a JDBC call or invoking a web service,
such operations generally take up a lot of CPU time leading to keeping a Thread engaged for
the same. This Thread allocated for a request is blocked waiting for the result of the long
operation and hence can lead to resource starvation when many such requests are engaged
by the server.
This and other problems which come with servlet handling long running tasks can be
mitigated by using Asynchronous servlet. An asynchronous servlet releases the Thread back
to the server pool and lets the long running task to proceed in the back ground. This long
running task takes with it a context object which can be used to intimate the server of the
availability of the result and this result can then be relayed back to the client from the
server. Such process of server pushing the data to the client is called “Server Push” or
“Comet” which is complimentary to “Ajax” which is a client side pull.
In this post I will show you how to create a Asynchronous Servlet and then make an Ajax
call from the JSP to this servlet. And the JSP will display the output from the servlet. But
before I go into that let me list out the classes which are used for creating Asynchronous
servlet so that we have an idea of these classes before looking into the code.

Classes used for creating Asynchronous Servlet


AsyncContext: From the Javadoc:

Class representing the execution context for an asynchronous operation that was initiated
on a ServletRequest.

An AsyncContext is created and initialized by a call to ServletRequest#startAsync() or


ServletRequest#startAsync(ServletRequest, ServletResponse). Repeated invocations of
these methods will return the same AsyncContext instance, reinitialized as appropriate.

AsyncListener: From the Javadoc:


Listener that will be notified in the event that an asynchronous operation initiated on a
ServletRequest to which the listener had been added has completed, timed out, or resulted
in an error.

© Aptech Ltd Version 1.0 56 of 194


Web Component Development Using Java References

The AsyncContext object holds the state of the request and response. Either the request
and response object is taken from the current context or one can provide their request and
response objects while initiating the asynchronous operation.

Creating the Long running task


Lets now create a long running task which has to be invoked from our servlet. This long
running task implements Runnable so that it can be handed over to a Thread pool to be
executed. Also this task takes in a AsyncContext object which is provided by the servlet.
Lets look at the code for our long running task:

1import java.io.IOException;

2 import java.io.PrintWriter;

3 import javax.servlet.AsyncContext;

4 /**

5 * Long running task which is to be invoked by our servlet.

6 */

7 public class DemoAsyncService implements Runnable {

9 /**

10 * The AsyncContext object for getting the request and response

11 * objects. Provided by the servlet.

12 */

13 private AsyncContext aContext;

14

15 public DemoAsyncService(AsyncContext aContext) {

16 this.aContext = aContext;

17 }

18

19 @Override

20 public void run() {

21 PrintWriter out = null;

© Aptech Ltd Version 1.0 57 of 194


Web Component Development Using Java References

22

23 try {

//Retrieve the type parameter from the request. This is passed in the
24
URL.

25 String typeParam = aContext.getRequest().getParameter("type");

26

//Retrieve the counter paramter from the request. This is passed in


27
the URL.

28 String counter = aContext.getRequest().getParameter("counter");

29

System.out.println("Starting the long running task:


30
Type="+typeParam+", Counter: "+counter);

31

32 out = aContext.getResponse().getWriter();

33

34 //Sleeping the thread so as to mimic long running task.

35 Thread.sleep(5000);

36

37 /**

38 * Doing some operation based on the type parameter.

39 */

40 switch (typeParam) {

41 case "1":

42 out.println("This process invoked for "+ counter +" times.");

43 break;

44 case "2":

out.println("Some other process invoked for "+ counter +"


45
times.");

46 break;

© Aptech Ltd Version 1.0 58 of 194


Web Component Development Using Java References

47 default:

48 out.println("Ok... nothing asked of.");

49 break;

50 }

51

System.out.println("Done processing the long running task:


52
Type="+typeParam+", Counter: "+counter);

53

54 /**

* Intimating the Web server that the asynchronous task is complete


55
and the

56 * response to be sent to the client.

57 */

58 aContext.complete();

59

60 } catch (IOException |InterruptedException ex) {

61 ex.printStackTrace();

62 }

63 finally{

64 out.close();

65 }

66 }

67 }

The important parts in the above code have been highlighted- namely line 25, line 28, line
32, line 58. In Line 25 and Line 28 we make use of the AsyncContext object to retrieve data
from the request object i.e HttpServletRequest object. In Line 32 we make use of the same
AsyncContext object to obtain the output stream from the response object i.e
HttpServletResponse object. The Line 58 is a bit interesting as this is the main part of the
asynchronous processing. This line says to the web server that the asynchronous processing
is completed and the response can be sent back to the client. The other way to let this
happen is by invoking: aContext.dispatch() method.

© Aptech Ltd Version 1.0 59 of 194


Web Component Development Using Java References

Creating the Asynchronous servlet


Now that we have a long running task to be invoked, its time to write our Asynchronous
servlet. Asynchronous servlet is not much different from the usual servlet. To let the
application server know that the servlet is asynchronous we have to set the asyncSupported
attribute in the @WebServlet annotation to true. Or if you are using a Deployment
descriptor i.e web.xml file to register your servlet then by adding tag within the servlet
registration xml code we can let the server know that the given servlet is asynchronous.

Once we have done the identification for the asynchronous servlet, we need to get the
AsyncContext object and then fire the long running task from within the servlet. When we
fire the asynchronous operation we can register a callback which will be invoked as and
when our operation is completed or timed out or runs into some error. Lets look at the code
for the servlet:
/**
2 * Our Asynchronous servlet with URL pattern = /asyncHello
3 */
4 @WebServlet(name = "DemoAsyncServlet",
5 urlPatterns = {"/asyncHello"},
6 asyncSupported = true)
7 public class DemoAsyncServlet extends HttpServlet {
8
9 /**
10 * Processes requests for both HTTP
11 * <code>GET</code> and
12 * <code>POST</code> methods.
13 *
14 * @param request servlet request
15 * @param response servlet response
16 * @throws ServletException if a servlet-specific error occurs
17 * @throws IOException if an I/O error occurs
18 */
protected void processRequest(HttpServletRequest request,
19
HttpServletResponse response)
20 throws ServletException, IOException {
21
System.out.println("Async Servlet with thread: " +
22
Thread.currentThread().toString());
23
//Starting the asynchronous handling and obtaining the AsyncContext
24
object.
25 AsyncContext ac = request.startAsync();
26
//Registering a listener with the AsyncContext object to listen to
27
events
28 //from the AsyncContext object.

© Aptech Ltd Version 1.0 60 of 194


Web Component Development Using Java References

29 ac.addListener(new AsyncListener() {
30 @Override
31 public void onComplete(AsyncEvent event) throws IOException {
32 System.out.println("Async complete");
33 }
34
35 @Override
36 public void onTimeout(AsyncEvent event) throws IOException {
37 System.out.println("Timed out...");
38 }
39
40 @Override
41 public void onError(AsyncEvent event) throws IOException {
42 System.out.println("Error...");
43 }
44
45 @Override
46 public void onStartAsync(AsyncEvent event) throws IOException {
47 System.out.println("Starting async...");
48 }
49 });
50
51 /**
* Scheduling our Long running process using an inbuilt ThreadPool.
52
Note
* that we are passing the AsyncContext object to our long running
53
process:
54 * DemoAsyncService.
55 */
ScheduledThreadPoolExecutor executer
56
= new ScheduledThreadPoolExecutor(10);
57 executer.execute(new DemoAsyncService(ac));
58 System.out.println("Servlet completed request handling");
59
60 }
61
62 /**
63 * Handles the HTTP
64 * <code>GET</code> method.
65 *
66 * @param request servlet request
67 * @param response servlet response
68 * @throws ServletException if a servlet-specific error occurs

© Aptech Ltd Version 1.0 61 of 194


Web Component Development Using Java References

69 * @throws IOException if an I/O error occurs


70 */
71 @Override
protected void doGet(HttpServletRequest request, HttpServletResponse
72
response)
73 throws ServletException, IOException {
74 processRequest(request, response);
75 }
76
77 }
In the above code the interesting pieces of code are: Line 6, Line 25, Line 29, Line 57. In
Line 6 we are declaring the servlet to be an asynchronous one. In Line 25 and Line 29 we
are setting up the asynchronous context and registering an listener respectively. And in Line
57 we are launching our long running process from the servlet.

Invoking the Asynchronous servlet from the JSP


Lets go ahead and make an Ajax request to our asynchronous servlet. In our JSP we will
have 2 buttons which on clicking them will updated the UI with some data from the server.
Lets look at the JSP code for asyncSample.jsp:

1<%@page contentType="text/html" pageEncoding="UTF-8"%>


2 <!DOCTYPE html>
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6 <title>JSP Page</title>
7 <script src="asyncSample.js"></script>
8 </head>
9 <body>
10 <h1>Hello World!</h1>
11 <input type="button" id="ajaxBt1" value="Update data" /> <br/>
12 <div id="req1Response"></div>
13 <input type="button" id="ajaxBt2" value="Update some other data" />
14 <div id="req2Response"></div>
15 </body>
16 </html>
And we do the event handling binding and setting up the Ajax calls in a different Javascript
file: asyncSample.js:
1 window.onload = setupEventHandlers;

3 //Counters to record the number of times the buttons were clicked.

4 var counter1;

© Aptech Ltd Version 1.0 62 of 194


Web Component Development Using Java References

5 var counter2;

7 //setting up the event handlers for the button

8 function setupEventHandlers() {

9 counter1 = 1;

10 counter2 = 1;

11 var ajaxBtn1 = document.getElementById("ajaxBt1");

12 var ajaxBtn2 = document.getElementById("ajaxBt2");

13 ajaxBtn1.onclick = handleAjaxBtn1;

14 ajaxBtn2.onclick = handleAjaxBtn2;

15

16 }

17

18 //Event handlers for the buttons

19

20 function handleAjaxBtn1(){

21 var xmlhrObj = new XMLHttpRequest();

xmlhrObj.open("GET", "http://localhost:8080/DemoApplication/asyncHello?type=1&counter=
22
+counter1, true);

23 counter1++;

24 xmlhrObj.onreadystatechange = function(){

25 if(xmlhrObj.readyState == 4 && xmlhrObj.status == 200){

26 var div1 = document.getElementById("req1Response");

27 div1.innerHTML = xmlhrObj.responseText;

28 }

29 };

30 xmlhrObj.send();

31 }

32

© Aptech Ltd Version 1.0 63 of 194


Web Component Development Using Java References

33 function handleAjaxBtn2(){

34 var xmlhrObj = new XMLHttpRequest();

xmlhrObj.open("GET", "http://localhost:8080/DemoApplication/asyncHello?type=2&counter=
35
+counter2, true);

36 counter2++;

37 xmlhrObj.onreadystatechange = function(){

38 if(xmlhrObj.readyState == 4 && xmlhrObj.status == 200){

39 var div2 = document.getElementById("req2Response");

40 div2.innerHTML = xmlhrObj.responseText;

41 }

42 };

43 xmlhrObj.send();
The above code does the following:
1. Fetches the buttons declared in the JSP using their IDs.
2. Registers the click handlers for these buttons.
3. The click handlers then make Ajax requests to our servlet.
4. The Ajax callbacks then update the UI with the output sent from the server.

And once you click on different buttons you would see the UI changing to:

~~~End of Article~~~

© Aptech Ltd Version 1.0 64 of 194


Web Component Development Using Java References

Session 7: Introduction to JSP

Scriptlets

Source http://www.jsptut.com/Scriptlets.jsp

Date of 02/04/2015
Retrieval:

We have already seen how to embed Java expressions in JSP pages by putting them
between the <%= and %> character sequences.

But it is difficult to do much programming just by putting Java expressions inside HTML.

JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your
Java code between <% and %> characters (just like expressions, but without the = sign at
the start of the sequence.)

This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any
HTML (though it can, as we will see down below.) A scriptlet contains Java code that is
executed every time the JSP is invoked.

Here is a modified version of our JSP from previous section, adding in a scriptlet.
<HTML>
<BODY>
<%
// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>

If you run the above example, you will notice the output from the "System.out.println" on
the server log. This is a convenient way to do simple debugging (some servers also have
techniques of debugging the JSP in the IDE. See your server's documentation to see if it
offers such a technique.) By itself a scriptlet does not generate HTML. If a scriptlet wants
to generate HTML, it can use a variable called "out". This variable does not need to be
declared. It is already predefined for scriptlets, along with some other variables. The
following example shows how the scriptlet can generate HTML output.
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"

© Aptech Ltd Version 1.0 65 of 194


Web Component Development Using Java References

System.out.println( "Evaluating date now" );


java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
Here, instead of using an expression, we are generating the HTML directly by printing to the
"out" variable. The "out" variable is of type javax.servlet.jsp.JspWriter. Another very
useful pre-defined variable is "request". It is of type
javax.servlet.http.HttpServletRequest

A "request" in server-side processing refers to the transaction between a browser and the
server. When someone clicks or enters a URL, the browser sends a "request" to the server
for that URL, and shows the data returned. As a part of this "request", various data is
available, including the file the browser wants from the server, and if the request is coming
from pressing a SUBMIT button, the information the user has entered in the form fields.

The JSP "request" variable is used to obtain information from the request as sent by the
browser. For instance, you can find out the name of the client's host (if available, otherwise
the IP address will be returned.) Let us modify the code as shown:

<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</BODY>
</HTML>

A similar variable is "response". This can be used to affect the response being sent to the
browser. For instance, you can call response.sendRedirect( anotherUrl ); to send a
response to the browser that it should load a different URL. This response will actually go
all the way to the browser. The browser will then send a different request, to "anotherUrl".
This is a little different from some other JSP mechanisms we will come across, for including
another page or forwarding the browser to another page.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 66 of 194


Web Component Development Using Java References

JSP Directive: page and include

Source http://www-inf.it-
sudparis.eu/SIMBAD/courses/doku.php?id=teaching_assistant:servlet-jsp:jsp-
directive
Date of 02/04/2015
Retrieval:

JSP directives provide directions and instructions to the container, telling it how to handle
certain aspects of JSP processing. In this tutorial, we will study the page directive and
include directive in JSP.

Page directive: <%@ page attribute="value" %>

1. A page directive defines page-dependent attributes, such as scripting language,


error page, and buffering requirements.
2. Some common used attributes are: import, contentType, errorPage and session.
3. Open the jsplabs project.
4. Right click on the WebContent folder, select New→JSP file.
5. Name it pagedirective.jsp and click Finish.
6. Add the following codes between the <body> tags.

<%@ page import="java.util.*,java.text.*" %>


<%
Date date = new Date();
// if we do not use the page import directive,
// we will write: java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>

7. Save the file.


8. Run it by right clicking on it then selecting Run As→Run on Server. Select Finish.
9. The current time will be presented on your web browser at the URL:
http://localhost:8080/jsplabs/pagedirective.jsp
10. Have a look on the first line of the pagedirective.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

11. It is also a page directive. Change text/html to text/xml and remove


the meta tag. Then refresh the page
http://localhost:8080/jsplabs/pagedirective.jsp to see what will change.

© Aptech Ltd Version 1.0 67 of 194


Web Component Development Using Java References

12. Now, we are going to examin the errorPage directive.


13. Change the text/xml back to text/html.
14. Replace the current codes between the <body> tags by the following codes:
<%!
private double toDouble(String value) {
return(Double.parseDouble(value));
}
%>
<%= toDouble("two") %>
15. Save the file and refresh the URL: http://localhost:8080/jsplabs/pagedirective.jsp.
You will get errors.
16. Now, create in the WebContent folder a file: error.jsp and simply insert a text
“Error!” between the <body> tags.
17. Back to the pagedirective.jsp, insert the following line right after the first
<body> tag.

<%@ page errorPage="error.jsp" %>

18. Save the file and refresh


the URL: http://localhost:8080/jsplabs/pagedirective.jsp.
Include directive: <%@ include attribute="value" %>
1. An include directive is used to include other JSP pages, HTML or text contents into a
current JSP.
2. Right click on the WebContent folder, select New→JSP file.
3. Name it includedirective.jsp and click Finish.
4. Add the following codes between the <body> tags.
Page content is here
<%@ include file="footer.jsp" %>
5. Save the file.
6. Create another JSP file in the same WebContent folder, name it footer.jsp.
7. Remove all current content and insert the following codes:

<%@ page import="java.util.Date" %>


<%-- The following become fields in each servlet that
results from a JSP page that includes this file. --%>
<%!
private int accessCount = 0;
private Date accessDate = new Date();
private String accessHost = "<I>No previous access</I>";
%>
<P>
<HR>
This page &copy; 2008 <A HREF="http//www.my-company.com/">my-
company.com</A>.

© Aptech Ltd Version 1.0 68 of 194


Web Component Development Using Java References

This page has been accessed <%= ++accessCount %> times since server
reboot.
It was most recently accessed from <%= accessHost %> at <%= accessDate
%>.
<% accessHost = request.getRemoteHost(); %> <% accessDate = new Date();
%>
<%@ page import="java.util.Date" %>
<%-- The following become fields in each servlet that
results from a JSP page that includes this file. --%>
<%!
private int accessCount = 0;
private Date accessDate = new Date();
private String accessHost = "<I>No previous access</I>";
%>
<P>
<HR>
This page &copy; 2008 <A HREF="http//www.my-company.com/">my-
company.com</A>.
This page has been accessed <%= ++accessCount %> times since server
reboot.
It was most recently accessed from <%= accessHost %> at <%= accessDate
%>.
<% accessHost = request.getRemoteHost(); %> <% accessDate = new Date();
%>

8. Save the file.


9. Run the includedirective.jsp file by right clicking on it then selecting Run As→Run
on Server. Select Finish.
10. The page including the footer will be presented on your web browser at the URL:
http://localhost:8080/jsplabs/includedirective.jsp

~~~ End of Article ~~~

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 69 of 194


Web Component Development Using Java References

Session 8: JSP Implicit Objects

Implicit Objects

Source https://docs.oracle.com/cd/E19316-01/819-3669/bnaij/index.html

Date of 02/04/2015
Retrieval:

The JSP expression language defines a set of implicit objects:

 pageContext: The context for the JSP page. Provides access to various objects including:

 servletContext: The context for the JSP page’s servlet and any web components
contained in the same application.
 session: The session object for the client.
 request: The request triggering the execution of the JSP page.
 response: The response returned by the JSP page.

In addition, several implicit objects are available that allow easy access to the following
objects:

 param: Maps a request parameter name to a single value


 paramValues: Maps a request parameter name to an array of values
 header: Maps a request header name to a single value
 headerValues: Maps a request header name to an array of values
 cookie: Maps a cookie name to a single cookie
 initParam: Maps a context initialization parameter name to a single value

Finally, there are objects that allow access to the various scoped variables using scope objects.

 pageScope: Maps page-scoped variable names to their values


 requestScope: Maps request-scoped variable names to their values
 sessionScope: Maps session-scoped variable names to their values
 applicationScope: Maps application-scoped variable names to their values

JSP 2.1 provides two EL resolvers to handle expressions that reference these
objects: ImplicitObjectELResolver and ScopedAttributeELResolver.

A variable that matches one of the implicit objects is evaluated


by ImplicitObjectResolver, which returns the implicit object. This resolver only handles
expressions with a base of null. What this means for the following expression is that
the ImplicitObjectResolver resolves thesessionScope implicit object only. Once the implicit

© Aptech Ltd Version 1.0 70 of 194


Web Component Development Using Java References

object is found, the MapELResolver instance resolves the profile attribute because
the profile object represents a map.

${sessionScope.profile}

ScopedAttributeELResolver evaluates a single object that is stored in scope.


Like ImplicitObjectELResolver, it also only evaluates expressions with a base of null. This
resolver essentially looks for an object in all of the scopes until it finds it, according to the
behavior of PageContext.findAttribute(String). For example, when evaluating the
expression ${product}, the resolver will look for product in the page, request, session, and
application scopes and will return its value. If product is not found, null is returned.

When an expression references one of the implicit objects by name, the appropriate object
is returned instead of the corresponding attribute. For example, ${pageContext} returns
the PageContext object, even if there is an existing pageContext attribute containing some
other value.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 71 of 194


Web Component Development Using Java References

Session 9: Standard Actions and JavaBeans

JavaBeans Concepts

Source http://da2i.univ-lille1.fr/doc/tutorial-java/javabeans/whatis/index.html

Date of 24/07/2014
Retrieval:

The JavaBeans™ architecture is based on a component model which enables developers to


create software units called components. Components are self-contained, reusable software
units that can be visually assembled into composite components, applets, applications, and
servlets using visual application builder tools. JavaBean components are known as beans.

A set of APIs describes a component model for a particular language. The JavaBeans API
specificationdescribes the core detailed elaboration for the JavaBeans component
architecture.

Beans are dynamic in that they can be changed or customized. Through the design mode of
a builder tool you can use the Properties window of the bean to customize the bean and
then save (persist) your beans using visual manupulation. You can select a bean from the
toolbox, drop it into a form, modify its appearance and behavior, define its interaction with
other beans, and combine it and other beans into an applet, application, or a new bean.

The following list briefly describes key bean concepts.

 Builder tools discover a bean's features (that is, its properties, methods, and events)
by a process known as introspection. Beans support introspection in two ways:
o By adhering to specific rules, known as design patterns, when naming bean
features. The Introspector class examines beans for these design patterns to
discover bean features. The Introspector class relies on the core reflection
API. The trail The Reflection API is an excellent place to learn about reflection.
o By explicitly providing property, method, and event information with a related
bean information class. A bean information class implements the BeanInfo
interface. A BeanInfo class explicitly lists those bean features that are to be
exposed to application builder tools.

 Properties are the appearance and behavior characteristics of a bean that can be
changed at design time. Builder tools introspect on a bean to discover its properties
and expose those properties for manipulation.

© Aptech Ltd Version 1.0 72 of 194


Web Component Development Using Java References

 Beans expose properties so they can be customized at design time. Customization is


supported in two ways: by using property editors, or by using more sophisticated
bean customizers.

 Beans use events to communicate with other beans. A bean that is to receive events
(a listener bean) registers with the bean that fires the event (a source bean). Builder
tools can examine a bean and determine which events that bean can fire (send) and
which it can handle (receive). Persistence enables beans to save and restore their
state. After changing a bean's properties, you can save the state of the bean and
restore that bean at a later time with the property changes intact. The JavaBeans
architecture uses Java Object Serialization to support persistence.

 A bean's methods are no different from Java methods, and can be called from other
beans or a scripting environment. By default all public methods are exported.

Beans vary in functionality and purpose. You have probably met some of the following
beans in your programming practice:

 GUI (graphical user interface)


 Non-visual beans, such as a spelling checker
 Animation applet
 Spreadsheet application

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 73 of 194


Web Component Development Using Java References

Beans and For m Processing

Source http://www.jsptut.com/forms.jsp

Date of 02/04/2015
Retrieval:

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


<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

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.

© Aptech Ltd Version 1.0 74 of 194


Web Component Development Using Java References

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.

© Aptech Ltd Version 1.0 75 of 194


Web Component Development Using Java References

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


<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>

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..


<jsp:useBean id="user" class="user.UserData" scope="session"/>
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>

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.

© Aptech Ltd Version 1.0 76 of 194


Web Component Development Using Java References

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.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 77 of 194


Web Component Development Using Java References

Session 10: Model-View-Controller Architecture


Model, View, Controller (MVC)

Source http://da2i.univ-lille1.fr/doc/tutorial-java/javabeans/whatis/index.html

Date of 24/07/2014
Retrieval:

In the MVC architecture, Java classes are developed as models, servlets play as controllers
and JSP are views. In this tutorial, we will develop a simple MVC application based on Java
servlet and JSP.

Creating Model

1. Create a new Dynamic Web Project, name it servlet-jsp.


2. In this project, create a new package, name it mvc.servlet.jsp.
3. In this package, create a new class, name it Model.
4. We will create two function to compute the square and the factorial of an integer
number. Add the following codes to the Model class

public int square (int x){


return x*x;
}

public int factorial (int x) {


if (x<0) return 0;
int fact=1;
for (int i=1; i<=x; i++)
fact*=i;
return fact;
}

5. Save the file.

Creating Controller

© Aptech Ltd Version 1.0 78 of 194


Web Component Development Using Java References

1. Right click on the mvc.servlet.jsp package, select New→Servlet. Name


it: Controller.
2. Insert the following codes in the doGet(…) function

int num = Integer.parseInt(request.getParameter("value"));


String method = request.getParameter("method");

Model m = new Model();

RequestDispatcher dispatcher;
HttpSession session = request.getSession();

if (method.equals("square")){
session.setAttribute("square", m.square(num));
dispatcher = request.getRequestDispatcher("square.jsp");
}
else{
session.setAttribute("factorial", m.factorial(num));
dispatcher = request.getRequestDispatcher("factorial.jsp");
}
dispatcher.forward(request, response);

Creating View

1. Right click on the WebContent folder, select New→JSP file. Name it index.jsp.
2. Similarly create other two files: square.jsp and factorial.jsp.
3. Open the index.jsp file, insert the following codes between the <body> tags:

<form action="Controller" method="GET">


Input an integer: <input type="text" name="value"> <br>
<input type="radio" name="method" value="square" checked> Square <br>
<input type="radio" name="method" value="factorial"> Factorial<br>

<input type="submit" value="Calculate">


</form>

© Aptech Ltd Version 1.0 79 of 194


Web Component Development Using Java References

4. Save the file.


5. Open the square.jsp file, insert the following codes between the <body> tags:

Square result: <%= session.getAttribute("square") %>

6. Save the file.


7. Open the factorial.jsp file, insert the following codes between the <body> tags:

Factorial result: <%= session.getAttribute("factorial") %>

8. Save the file.

Running the project

1. Right click on the index.jsp file, select Run As→Run on Server.


2. Your application is opened at: http://localhost:8080/servlet-jsp/index.jsp

3. Type an integer number, select a method and click on Calculate, you will get the
corresponding result.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 80 of 194


Web Component Development Using Java References

Session 11: JSP Expressions Language

Unified Expression Language

Source http://da2i.univ-lille1.fr/doc/tutorial-java/javabeans/whatis/index.html

Date of 24/07/2014
Retrieval:

The primary new feature of JSP 2.1 is the unified expression language (unified EL), which
represents a union of the expression language offered by JSP 2.0 and the expression
language created for JavaServer Faces technology (see Chapter 10, JavaServer Faces
Technology) version 1.0.

The expression language introduced in JSP 2.0 allows page authors to use simple
expressions to dynamically read data from JavaBeans components. For example, the test
attribute of the following conditional tag is supplied with an EL expression that compares the
number of items in the session-scoped bean named cart with 0.

<c:if test="${sessionScope.cart.numberOfItems > 0}">


...
</c:if>
As explained in The Life Cycle of a JSP Page, JSP supports a simple request/response life
cycle, during which a page is executed and the HTML markup is rendered immediately.
Therefore, the simple, read-only expression language offered by JSP 2.0 was well suited to
the needs of JSP applications.

JavaServer Faces technology, on the other hand, features a multiphase life cycle designed
to support its sophisticated UI component model, which allows for converting and validating
component data, propagating component data to objects, and handling component events.
To facilitate these functions, JavaServer Faces technology introduced its own expression
language that included the following functionality:

 Deferred evaluation of expressions


 The ability to set data as well as get data
 The ability to invoke methods

These two expression languages have been unified for a couple reasons. One reason is so
that page authors can mix JSP content with JavaServer Faces tags without worrying about
conflicts caused by the different life cycles these technologies support. Another reason is so
that other JSP-based technologies could make use of the additional features similarly to the
way JavaServer Faces technology uses them. In fact, although the standard JSP tags and
static content continue to use only those features present in JSP 2.0, authors of JSP custom
tags can create tags that take advantage of the new set of features in the unified expression
language.

© Aptech Ltd Version 1.0 81 of 194


Web Component Development Using Java References

To summarize, the new, unified expression language allows page authors to use simple
expressions to perform the following tasks:

 Dynamically read application data stored in JavaBeans components, various data


structures, and implicit objects
 Dynamically write data, such as user input into forms, to JavaBeans components
 Invoke arbitrary static and public methods
 Dynamically perform arithmetic operations

The unified EL also allows custom tag developers to specify which of the following kinds of
expressions that a custom tag attribute will accept:

 Immediate evaluation expressions or deferred evaluation expressions. An


immediate evaluation expression is evaluated immediately by the JSP engine. A
deferred evaluation expression can be evaluated later by the underlying technology
using the expression language.
 Value expression or method expression. A value expression references data,
whereas a method expression invokes a method.
 Rvalue expression or Lvalue expression. An rvalue expression can only read a
value, whereas an lvalue expression can both read and write that value to an
external object.

Finally, the unified EL also provides a pluggable API for resolving expressions so that
application developers can implement their own resolvers that can handle expressions not
already supported by the unified EL.

Immediate and Deferred Evaluation Syntax


The unified EL supports both immediate and deferred evaluation of expressions. Immediate
evaluation means that the JSP engine evaluates the expression and returns the result
immediately when the page is first rendered. Deferred evaluation means that the
technology using the expression language can employ its own machinery to evaluate the
expression sometime later during the page’s life cycle, whenever it is appropriate to do so.

Those expressions that are evaluated immediately use the ${} syntax, which was
introduced with the JSP 2.0 expression language. Expressions whose evaluation is deferred
use the #{} syntax, which was introduced by JavaServer Faces technology.

Because of its multiphase life cycle, JavaServer Faces technology uses deferred evaluation
expressions. During the life cycle, component events are handled, data is validated, and
other tasks are performed, all done in a particular order. Therefore, it must defer evaluation
of expressions until the appropriate point in the life cycle.

Other technologies using the unified EL might have different reasons for using deferred
expressions.

© Aptech Ltd Version 1.0 82 of 194


Web Component Development Using Java References

Immediate Evaluation
All expressions using the ${} syntax are evaluated immediately. These expressions can only
be used within template text or as the value of a JSP tag attribute that can accept runtime
expressions.

The following example shows a tag whose value attribute references an immediate
evaluation expression that gets the total price from the session-scoped bean named cart:

<fmt:formatNumber value="${sessionScope.cart.total}"/>
The JSP engine evaluates the expression, ${sessionScope.cart.total}, converts it, and
passes the returned value to the tag handler.

Immediate evaluation expressions are always read-only value expressions. The expression
shown above can only get the total price from the cart bean; it cannot set the total price.

Deferred Evaluation
Deferred evaluation expressions take the form #{expr} and can be evaluated at other
phases of a page life cycle as defined by whatever technology is using the expression. In
the case of JavaServer Faces technology, its controller can evaluate the expression at
different phases of the life cycle depending on how the expression is being used in the page.

The following example shows a JavaServer Faces inputText tag, which represents a text
field component into which a user enters a value. The inputText tag’s value attribute
references a deferred evaluation expression that points to the name property of the
customer bean.

<h:inputText id="name" value="#{customer.name}" />


For an initial request of the page containing this tag, the JavaServer Faces implementation
evaluates the #{customer.name} expression during the render response phase of the life
cycle. During this phase, the expression merely accesses the value of name from the
customer bean, as is done in immediate evaluation.

For a postback, the JavaServer Faces implementation evaluates the expression at different
phases of the life cycle, during which the value is retrieved from the request, validated, and
propagated to the customer bean.

As shown in this example, deferred evaluation expressions can be value expressions that
can be used to both read and write data. They can also be method expressions. Value
expressions (both immediate and deferred) and method expressions are explained in the
next section.

Value and Method Expressions


The unified EL defines two kinds of expressions: value expressions and method expressions.
Value expressions can either yield a value or set a value. Method expressions reference
methods that can be invoked and can return a value.

© Aptech Ltd Version 1.0 83 of 194


Web Component Development Using Java References

Value Expressions
Value expressions can be further categorized into rvalue and lvalue expressions. Rvalue
expressions are those that can read data, but cannot write it. Lvalue expressions can both
read and write data.

All expressions that are evaluated immediately use the ${} delimiters and are always rvalue
expressions. Expressions whose evaluation can be deferred use the #{} delimiters and can
act as both rvalue and lvalue expressions. Consider these two value expressions:

<taglib:tag value="${customer.name}" />


<taglib:tag value="#{customer.name}" />

The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation
syntax. The first expression accesses the name property, gets its value, and the value is
added to the response and rendered on the page. The same thing can happen with the
second expression. However, the tag handler can defer the evaluation of this expression to
a later time in the page life cycle, if the technology using this tag allows it.

In the case of JavaServer Faces technology, the latter tag’s expression is evaluated
immediately during an initial request for the page. In this case, this expression acts as an
rvalue expression. During a postback, this expression can be used to set the value of the
name property with user input. In this situation, the expression acts as an lvalue
expression.

Referencing Objects Using Value Expressions


Both rvalue and lvalue expressions can refer to the following objects and their properties or
attributes:

 JavaBeans components

 Collections

 Java SE enumerated types

 Implicit objects

To refer to these objects, you write an expression using a variable name with which you
created the object. The following expression references a JavaBeans component called
customer.

${customer}
The web container evaluates a variable that appears in an expression by looking up its value
according to the behavior of PageContext.findAttribute(String), where the String
argument is the name of the variable. For example, when evaluating the expression
${customer}, the container will look for customer in the page, request, session, and
application scopes and will return its value. If customer is not found, null is returned. A

© Aptech Ltd Version 1.0 84 of 194


Web Component Development Using Java References

variable that matches one of the implicit objects described in Implicit Objects will return
that implicit object instead of the variable’s value.

You can alter the way variables are resolved with a custom EL resolver, which is a new
feature of the unified EL. For instance, you can provide an EL resolver that intercepts
objects with the name customer, so that ${customer} returns a value in the EL resolver
instead. However, you cannot override implicit objects in this way. See EL Resolvers for
more information on EL resolvers.

You can set the variable name, customer, when you declare the bean. See Creating and
Using a JavaBeans Component for information on how to declare a JavaBeans component
for use in your JSP pages.

To declare beans in JavaServer Faces applications, you use the managed bean facility. See
Backing Beans for information on how to declare beans for use in JavaServer Faces
applications.

When referencing an enum constant with an expression, you use a String literal. For
example, consider this Enum class:

public enum Suit {hearts, spades, diamonds, clubs}


To refer to the Suit constant, Suit.hearts with an expression, you use the String literal,
"hearts". Depending on the context, the String literal is converted to the enum constant
automatically. For example, in the following expression in which mySuit is an instance of
Suit, "hearts" is first converted to a Suit.hearts before it is compared to the instance.

${mySuit == "hearts"}
Referring to Object Properties Using Value Expressions
To refer to properties of a bean or an Enum instance, items of a collection, or attributes of
an implicit object, you use the . or [] notation, which is similar to the notation used by
ECMAScript.

So, if you wanted to reference the name property of the customer bean, you could use
either the expression ${customer.name} or the expression ${customer["name"]}. The part
inside the square brackets is a String literal that is the name of the property to reference.

You can use double or single quotes for the String literal. You can also combine the [] and .
notations, as shown here:

${customer.address["street"]}
Properties of an enum can also be referenced in this way. However, as with JavaBeans
component properties, the Enum class’s properties must follow JavaBeans component
conventions. This means that a property must at least have an accessor method called
get<Property> (where <Property> is the name of the property) so that an expression can
reference it.

© Aptech Ltd Version 1.0 85 of 194


Web Component Development Using Java References

For example, say you have an Enum class that encapsulates the names of the planets of our
galaxy and includes a method to get the mass of a planet. You can use the following
expression to reference the method getMass of the Planet Enum class:

${myPlanet.mass}
If you are accessing an item in an array or list, you must use either a literal value that can
be coerced to int or the [] notation with an int and without quotes. The following examples
could all resolve to the same item in a list or array, assuming that socks can be coerced to
int:

${customer.orders[1]}

${customer.orders.socks}

In contrast, an item in a Map can be accessed using a string literal key; no coercion is
required:

${customer.orders["socks"]}
An rvalue expression also refers directly to values that are not objects, such as the result of
arithmetic operations and literal values, as shown by these examples:

${"literal"}

${customer.age + 20}

${true}

${57}

The unified expression language defines the following literals:

 Boolean: true and false



 Integer: as in Java

 Floating point: as in Java

 String: with single and double quotes; " is escaped as \", ’ is escaped as \', and \ is
escaped as \\

 Null: null

You can also write expressions that perform operations on an enum constant. For example,
consider the following Enum class:

© Aptech Ltd Version 1.0 86 of 194


Web Component Development Using Java References

public enum Suit {club, diamond, heart, spade }

After declaring an enum constant called mySuit, you can write the following expression to
test if mySuit is spade:

${mySuit == "spade"}
When the EL resolving mechanism resolves this expression it will invoke the valueOf method
of the Enum class with the Suit class and the spade type, as shown here:

mySuit.valueOf(Suit.class, "spade"}
See JavaBeans Components for more information on using expressions to reference
JavaBeans components and their properties.

Where Value Expressions Can Be Used


Value expressions using the ${} delimiters can be used in the following places:

 In static text

 In any standard or custom tag attribute that can accept an expression

The value of an expression in static text is computed and inserted into the current output.
Here is an example of an expression embedded in static text:

<some:tag>
some text ${expr} some text
</some:tag>

If the static text appears in a tag body, note that an expression will not be evaluated if the
body is declared to be tagdependent (see Tags with Attributes).

Lvalue expressions can only be used in tag attributes that can accept lvalue expressions.

There are three ways to set a tag attribute value using either an rvalue or lvalue
expression:

 With a single expression construct:


<some:tag value="${expr}"/>
<another:tag value="#{expr}"/>
These expressions are evaluated and the result is coerced to the attribute’s expected type.

 With one or more expressions separated or surrounded by text:

<some:tag value="some${expr}${expr}text${expr}"/>
<another:tag value="some#{expr}#{expr}text#{expr}"/>

© Aptech Ltd Version 1.0 87 of 194


Web Component Development Using Java References

These kinds of expression are called a composite expressions. They are evaluated from
left to right. Each expression embedded in the composite expression is coerced to a String
and then concatenated with any intervening text. The resulting String is then coerced to the
attribute’s expected type.

With text only:

<some:tag value="sometext"/>
This expression is called a literal expression. In this case, the attribute’s String value is
coerced to the attribute’s expected type. Literal value expressions have special syntax rules.
See Literal Expressions for more information. When a tag attribute has an enum type, the
expression that the attribute uses must be a literal expression. For example, the tag
attribute can use the expression "hearts" to mean Suit.hearts. The literal is coerced to Suit
and the attribute gets the value Suit.hearts.

All expressions used to set attribute values are evaluated in the context of an expected
type. If the result of the expression evaluation does not match the expected type exactly, a
type conversion will be performed. For example, the expression ${1.2E4} provided as the
value of an attribute of type float will result in the following conversion:

Float.valueOf("1.2E4").floatValue()

Method Expressions
Another feature of the unified expression language is its support of deferred method
expressions. A method expression is used to invoke an arbitrary public method, which can
return a result. A similar feature of the unified EL is functions. Method expressions differ
from functions in many ways. Functions explains more about the differences between
functions and method expressions.

Method expressions primarily benefit JavaServer Faces technology, but they are available to
any technology that can support the unified expression language. Let’s take a look at how
JavaServer Faces technology employs method expressions.

In JavaServer Faces technology, a component tag represents a UI component on a page.


The component tag uses method expressions to invoke methods that perform some
processing for the component. These methods are necessary for handling events that the
components generate and validating component data, as shown in this example:

<h:form>
<h:inputText
id="name"
value="#{customer.name}"
validator="#{customer.validateName}"/>
<h:commandButton
id="submit"
action="#{customer.submit}" />
</h:form>

© Aptech Ltd Version 1.0 88 of 194


Web Component Development Using Java References

The inputText tag displays a UIInput component as a text field. The validator attribute of
this inputText tag references a method, called validateName, in the bean, called customer.
The TLD (see Tag Library Descriptors) that defines the inputText tag specifies what
signature the method referred to by the validator attribute must have. The same is true of
the customer.submit method referenced by the action attribute of the commandButton tag.
The TLD specifies that the submit method must return an Object instance that specifies
which page to navigate to next after the button represented by the commandButton tag is
clicked.

The validation method is invoked during the process validation phase of the life cycle,
whereas the submit method is invoked during the invoke application phase of the life cycle.
Because a method can be invoked during different phases of the life cycle, method
expressions must always use the deferred evaluation syntax.

Similarly to lvalue expressions, method expressions can use the . and [] operators. For
example, #{object.method} is equivalent to #{object["method"]}. The literal inside the []
is coerced to String and is used to find the name of the method that matches it. Once the
method is found, it is invoked or information about the method is returned.

Method expressions can be used only in tag attributes and only in the following ways:

 With a single expression construct, where bean refers to a JavaBeans component


and method refers to a method of the JavaBeans component:

<some:tag value="#{bean.method}"/>
The expression is evaluated to a method expression, which is passed to the tag
handler. The method represented by the method expression can then be invoked
later.

 With text only:

<some:tag value="sometext"/>
Method expressions support literals primarily to support action attributes in
JavaServer Faces technology. When the method referenced by this method
expression is invoked, it returns the String literal, which is then coerced to the
expected return type, as defined in the tag’s TLD.

Defining a Tag Attribute Type


Table 5-2 shows the three different kinds of tag attributes that accept EL expressions, and
gives examples of expressions they accept and the type definitions of the attributes that
must be added to the TLD. You cannot use #{} syntax for a dynamic attribute, meaning an
attribute that accepts dynamically-calculated values at runtime.

© Aptech Ltd Version 1.0 89 of 194


Web Component Development Using Java References

Table 5-2 Definitions of Tag Attributes That Accept EL Expressions

In addition to the tag attribute types shown in Table 5-2, you can also define an attribute to
accept both dynamic and deferred expressions. In this case, the tag attribute definition
contains both an rtexprvalue definition set to true and either a deferred-value or deferred-
method definition.

Deactivating Expression Evaluation


Because the patterns that identify EL expressions, ${ } and #{ }, were not reserved in the
JSP specifications before JSP 2.0, there might exist applications in which such patterns are
intended to pass through verbatim. To prevent the patterns from being evaluated, you can
deactivate EL evaluation using one of the following methods:

 Escape the #{ or ${ characters in the page.



 Configure the application with a JSP Property Group.

 Configure the page with the page directive.

© Aptech Ltd Version 1.0 90 of 194


Web Component Development Using Java References

To escape the #{ or ${ characters in the page, you use the \ character as follows:

some text \#{ some more\${ text


<my:tag someAttribute="sometext\#{more\${text" />

Another way to deactivate EL evaluation is by using a JSP property group to either allow the
#{ characters as a String literal using the deferred-syntax-allowed-as-literal subelement, or
to treat all expressions as literals using the el-ignored subelement:

<jsp-property-group>
<deferred-syntax-allowed-as-literal>
true
</deferred-syntax-allowed-as-literal>
</jsp-property-group>
or

<jsp-property-group>
<el-ignored>true</el-ignored>
</jsp-property-group>

Finally, you can configure the page with the page directive to either accept the #{
characters as String literals with the deferredSyntaxAllowedAsLiteral attribute, or to ignore
all EL expressions using the isELIgnored attribute:

<%@page ... deferredSyntaxAllowedAsLiteral="true" %>


or

<%@ page isELIgnored ="true" %>

The valid values of these attributes are true and false. If isELIgnored is true, EL expressions
are ignored when they appear in static text or tag attributes. If it is false, EL expressions
are evaluated by the container only if the attribute has rtexprvalue set to true or the
expression is a deferred expression.

The default value of isELIgnored varies depending on the version of the web application
deployment descriptor. The default mode for JSP pages delivered with a Servlet 2.4
descriptor is to evaluate EL expressions; this automatically provides the default that most
applications want. The default mode for JSP pages delivered using a descriptor from Servlet
2.3 or before is to ignore EL expressions; this provides backward compatibility.

Literal Expressions
A literal expression evaluates to the text of the expression, which is of type String. It does
not use the ${} or #{} delimiters.

If you have a literal expression that includes the reserved ${} or #{} syntax, you need to
escape these characters as follows.

© Aptech Ltd Version 1.0 91 of 194


Web Component Development Using Java References

By creating a composite expression as shown here:

${’${’}exprA}
#{’#{’}exprB}
The resulting values would then be the strings ${exprA} and #{exprB}.

The escape characters \$ and \# can be used to escape what would otherwise be treated as
an eval-expression:

\${exprA}
\#{exprB}
The resulting values would again be the strings ${exprA} and #{exprB}.

When a literal expression is evaluated, it can be converted to another type. Table 5-3 shows
examples of various literal expressions and their expected types and resulting values.

Table 5-3 Literal Expressions

Literal expressions can be evaluated immediately or deferred and can be either value or
method expressions. At what point a literal expression is evaluated depends on where it is
being used. If the tag attribute that uses the literal expression is defined as accepting a
deferred value expression, then the literal expression references a value and is evaluated at
a point in the life cycle that is determined by where the expression is being used and to
what it is referring.

In the case of a method expression, the method that is referenced is invoked and returns
the specified String literal. The commandButton tag of the Guess Number application uses a
literal method expression as a logical outcome to tell the JavaServer Faces navigation
system which page to display next. See Navigation Model for more information on this
example.

Resolving Expressions
The unified EL introduces a new, pluggable API for resolving expressions. The main pieces of
this API are:

 The ValueExpression class, which defines a value expression

 The MethodExpression class, which defines a method expression

© Aptech Ltd Version 1.0 92 of 194


Web Component Development Using Java References

 An ELResolver class that defines a mechanism for resolving expressions

 A set of ELResolver implementations, in which each implementation is responsible


for resolving expressions that reference a particular type of object or property

 An ELContext object that saves state relating to EL resolution, holds references to EL


resolvers, and contains context objects (such as JspContext) needed by the
underlying technology to resolve expressions

Most application developers will not need to use these classes directly unless they plan to
write their own custom EL resolvers. Those writing JavaServer Faces custom components
will definitely need to use ValueExpression and MethodExpression. This section details how
expressions are resolved for the benefit of these developers. It does not explain how to
create a custom resolver. For more information on creating custom resolvers, see the article

Process of Expression Evaluation


When a value expression that is included in a page is parsed during an initial request for the
page, a ValueExpression object is created to represent the expression. Then, the
ValueExpression object’s getValue method is invoked. This method will in turn invoke the
getValue method of the appropriate resolver. A similar process occurs during a postback
when setValue is called if the expression is an lvalue expression.

In the case of a method expression, a BeanELResolver is used to find the object that
implements the method to be invoked or queried. Similarly to the process for evaluating
value expressions, when a method expression is encountered, a MethodExpression object is
created. Subsequently, either the invoke or getMethodInfo method of the MethodExpression
object is called. This method in turn invokes the BeanELResolver object’s getValue method.
The getMethodInfo is mostly for use by tools.

After a resolver completes resolution of an expression, it sets the propertyResolved flag of


the ELContext to true so that no more resolvers are consulted.

EL Resolvers
At the center of the EL machinery is the extensible ELResolver class. A class that
implements ELResolver defines how to resolve expressions referring to a particular type of
object or property. In terms of the following expression, a BeanELResolver instance is
called the first time to find the base object, employee, which is a JavaBeans component.
Once the resolver finds the object, it is called again to resolve the property, lName of the
employee object.

${employee.lName}

The unified EL includes a set of standard resolver implementations. Table 5-4 lists these
standard resolvers and includes example expressions that they can resolve.

© Aptech Ltd Version 1.0 93 of 194


Web Component Development Using Java References

Depending on the technology using the unified EL, other resolvers might be available. In
addition, application developers can add their own implementations of ELResolver to support
resolution of expressions not already supported by the unified EL by registering them with
an application.

All of the standard and custom resolvers available to a particular application are collected in
a chain in a particular order. This chain of resolvers is represented by a
CompositeELResolver instance. When an expression is encountered, the
CompositeELResolver instance iterates over the list of resolvers and consults each resolver
until it finds one that can handle the expression.

If an application is using JSP technology, the chain of resolvers includes the


ImplicitObjectELResolver and the ScopedAttributeELResolver. These are described in
the following section.

Implicit Objects
The JSP expression language defines a set of implicit objects:

 pageContext: The context for the JSP page. Provides access to various objects
including:
 servletContext: The context for the JSP page’s servlet and any web components
contained in the same application. See Accessing the Web Context.
 session: The session object for the client. See Maintaining Client State.
 request: The request triggering the execution of the JSP page.
 response: The response returned by the JSP page. See Constructing Responses.
 param: Maps a request parameter name to a single value.
 paramValues: Maps a request parameter name to an array of values.
 header: Maps a request header name to a single value.
 headerValues: Maps a request header name to an array of values.
 cookie: Maps a cookie name to a single cookie.
 initParam: Maps a context initialization parameter name to a single value.

Finally, there are objects that allow access to the various scoped variables described in
Using Scope Objects.

 pageScope: Maps page-scoped variable names to their values.


 requestScope: Maps request-scoped variable names to their values.

© Aptech Ltd Version 1.0 94 of 194


Web Component Development Using Java References

 sessionScope: Maps session-scoped variable names to their values.


 applicationScope: Maps application-scoped variable names to their values.

JSP 2.1 provides two EL resolvers to handle expressions that reference these objects:
ImplicitObjectELResolver and ScopedAttributeELResolver.

A variable that matches one of the implicit objects is evaluated by


ImplicitObjectResolver, which returns the implicit object. This resolver only handles
expressions with a base of null. What this means for the following expression is that the
ImplicitObjectResolver resolves the sessionScope implicit object only. Once the implicit
object is found, the MapELResolver instance resolves the profile attribute because the
profile object represents a map.

${sessionScope.profile}
ScopedAttributeELResolver evaluates a single object that is stored in scope. Like
ImplicitObjectELResolver, it also only evaluates expressions with a base of null. This
resolver essentially looks for an object in all of the scopes until it finds it, according to the
behavior of PageContext.findAttribute(String). For example, when evaluating the expression
${product}, the resolver will look for product in the page, request, session, and application
scopes and will return its value. If product is not found, null is returned.

When an expression references one of the implicit objects by name, the appropriate object
is returned instead of the corresponding attribute. For example, ${pageContext} returns
the PageContext object, even if there is an existing pageContext attribute containing some
other value.

Operators
In addition to the . and [] operators discussed in Value and Method Expressions, the JSP
expression language provides the following operators, which can be used in rvalue
expressions only:

 Arithmetic: +, - (binary), *, / and div, % and mod, - (unary)


 Logical: and, &&, or, ||, not, !
 Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made
against other values, or against boolean, string, integer, or floating point literals.
 Empty: The empty operator is a prefix operation that can be used to determine
whether a value is null or empty.
 Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of
A.
 The precedence of operators highest to lowest, left to right is as follows:
 [] .
 () (used to change the precedence of operators)
 - (unary) not ! empty
 * / div % mod
 + - (binary)
 < > <= >= lt gt le ge

© Aptech Ltd Version 1.0 95 of 194


Web Component Development Using Java References

 == != eq ne
 && and
 || or
 ?:

Reserved Words
The following words are reserved for the JSP expression language and should not be used as
identifiers.

Note that many of these words are not in the language now, but they may be in the future,
so you should avoid using them.

Examples of EL Expressions
Table 5-5 contains example EL expressions and the result of evaluating them.

Table 5-5 Example Expressions

© Aptech Ltd Version 1.0 96 of 194


Web Component Development Using Java References

Functions
The JSP expression language allows you to define a function that can be invoked in an
expression. Functions are defined using the same mechanisms as custom tags.

At first glance, functions seem similar to method expressions, but they are different in the
following ways:

 Functions refer to static methods that return a value. Method expressions refer to
non-static, arbitrary public methods on objects.
 Functions are identified statically at translation time, whereas methods are identified
dynamically at runtime.
 Function parameters and invocations are specified as part of an EL expression. A
method expression only identifies a particular method. The invocation of that method
is not specified by the EL expression; rather, it is specified in the tag attribute
definition of the attribute using the method expression, as described in Defining a
Tag Attribute Type.

Using Functions
Functions can appear in static text and tag attribute values.

To use a function in a JSP page, you use a taglib directive to import the tag library
containing the function. Then you preface the function invocation with the prefix declared in
the directive.

For example, the date example page index.jsp imports the /functions library and invokes
the function equals in an expression:

<%@ taglib prefix="f" uri="/functions"%>


...
<c:when
test="${f:equals(selectedLocaleString,
localeString)}" >
In this example, the expression referencing the function is using immediate evaluation
syntax. A page author can also use deferred evaluation syntax to reference a function in an
expression, assuming that the attribute that is referencing the function can accept deferred
expressions.

If an attribute references a function with a deferred expression then the function is not
invoked immediately; rather, it is invoked whenever the underlying technology using the
function determines it should be invoked.

© Aptech Ltd Version 1.0 97 of 194


Web Component Development Using Java References

Defining Functions
To define a function, program it as a public static method in a public class. The
mypkg.MyLocales class in the date example defines a function that tests the equality of two
Strings as follows:

package mypkg;
public class MyLocales {

...
public static boolean equals( String l1, String l2 ) {
return l1.equals(l2);
}
}
Then map the function name as used in the EL expression to the defining class and function
signature in a TLD (see Chapter 8, Custom Tags in JSP Pages). The following functions.tld
file in the date example maps the equals function to the class containing the implementation
of the function equals and the signature of the function:
<function>
<name>equals</name>
<function-class>mypkg.MyLocales</function-class>
<function-signature>boolean equals( java.lang.String,
java.lang.String )</function-signature>
</function>
No two functions within a tag library can have the same name.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 98 of 194


Web Component Development Using Java References

Session 12: JavaServer Pages Standard Tag Library

JSTL Set tag examples or <c:set> in JSP- Java J2EE Tutorial

Source http://javarevisited.blogspot.in/2012/02/jstl-tag-examples-in-jsp-
java-j2ee.html

Date of 24/07/2014
Retrieval:

JSTL set tag or <c:set> also called as JSTL Core tag library is a good replacement of
<jsp:setProperty> jsp action which lacks lot of functionality and only allow you to set bean
property. you can not set Map's key value or create a scoped variable by using
<jsp:setProperty>. jstl <set> tag allows you to do all the stuff related to setting or
creating variables or attributes. by using JSTL <c:set> tag you can :

1) Set bean properties

2) Set Map values

3) Create Scoped variable on page, request, session or application scope.

But <c:set> comes with its own caveat like <c:set> can remove attributes or variable
if provided value is null or throw exceptions which we will here. we will also lots of
examples of JSTL tag <c:set> to understand what Set can do and how to use JSTL
<c:set> tag.

JSTL Core < c:set> tag

As I said earlier JSTL Set tag or <c:set> is use to set bean properties, map value and to
create scoped variables. <c:set> can be used in two different ways either by using "var" or
by using "target". var is used to define name of variable needs to be created or whose
values needs to be set. while "target" is used to denote Bean Object or Map whose values
needs to be set. here is a simple example of JSTL <c:set> tag

<c:set var="currency" value="USD" />

© Aptech Ltd Version 1.0 99 of 194


Web Component Development Using Java References

JSTL Example : How to create variable in session scope using <c:set> tag in JSP

Above example of <c:set> will create an attribute named "currency" with value "USD" in
default scope which is page scope. you can also create attribute into another scope say
session scope, in that case you need to specify scope with <c:set> attribute scope="". here
is an example of creating variable on session scope using jstl set tag:

<c:set var="currency" value="USD" scope="session" />

value of variable can also be a runtime expression e.g jsp expression or EL


expression. like the one which is shown in below example of set tag:

<c:set var="currency" value="${user.currency}" scope="session" />

here Container will copy bean property user.currency in "currency" variable.

JSTL Example : How to pass value in <c:set> tag body in JSP

Another variance of jstl <c:set> tag is that you can supply value in body instead of on
attribute line. some time when value is long, giving it on body makes code more readable.
here is example of supplying value on jstl set tag body:

<c:set var="currency" scope="session" >

USD,EUR,AUD,INR

</c:set>

JSTL Example : How to remove attribute using <c:set> in JSP

Keep in mind that <c:set> can also remove a variable or attribute if value resolves to "null"
during runtime. e.g. in below example

<c:set var="currency" value="${user.currency}" />

© Aptech Ltd Version 1.0 100 of 194


Web Component Development Using Java References

<c: set> tag of jstl will remove "currency" attribute from any scope if EL expression
${user.currency} will resolve to null.

JSTL Example : How to set bean property using JSTL <c:set> tag in JSP

All of above example were for setting attribute or creating variables, but <c:set> can also
be used to set bean properties or map value. in that case instead of "var" we need to use
"target" and "property" which will define bean and property name to be set. if "target" is
map than "property" is name of key and "value" is value for that key. What is worth noting
here is that <c:set target=""> must point to a real object and not the name of
object as it was with <jsp:useBean> action. if "target" doesn't resolve into object than web
container will throw exception. here is example of setting bean property using JSTL <c:set>
tag in JSP:

<c:set target="currencyMap" property="USA" value="USD">

this is equivalent to currencyMap.put("USA", "USD"); just like before you can also supply
value in body of jst <c:set> tag in jsp. here is another example of setting bean properties
using JSTL <c:set> tag :

<c:set target="trade" property="currency" value="USD">

this example will set currency property of bean named "trade" and equivalent to :

trade.setCurrency("USD");

You just need to make sure that target should resolve into real object.

JSTL <c:set> - Points to remember

Here are few important points to remember on <c:set> tag from JSTL core tag library. I
have seen we often overlooked these small subtle details which causes hard to find bugs in
JSP:

© Aptech Ltd Version 1.0 101 of 194


Web Component Development Using Java References

1) <c:set> can remove attribute if value="null".

2) Value for JSTL <c:set> tag can be specified in body also.

3) JSTL set tag value can be runtime expression include JSP expression or EL expression.

4) In target version of <c:set> if target is pointing to bean and property is not valid
property container will throw exception.

5) If variable pointed by "var" doesn't exists than JSTL <c:set> tag creates it for you only if
value is not null.

6) Scope attribute is optional in JSTL <c:set> tag and default scope is page scope.

These were some examples of JSTL core < c:set> or set tag. <c:set> is very
convenient and provides lots of key functionality required in JSP pages. I recommend using
<c:set> over < jsp:property> or JSP actions. Let me know if you come across any other
good example of <c:set> tag which we can include here.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 102 of 194


Web Component Development Using Java References

Session 13: JSP Custom Tags

JSP Tags
Source http://www.alethis.net/reference/java/jsptags.html#Custom_Tags

Date of 02/04/2015
Retrieval

Custom TagsCustgs

Two mechanisms now supported:

 classic - requires Java code, tag library descriptor


 tag files - tags are implemented in a JSP-like file, no descriptor needed

Typical tag scenarios:

 simple tag - no body or attributes


 simple tag with attributes - no body
 tag with body
 iterative tag
 tags with shared context

JSP 1.0 Tags


These tags are implemented via Java classes, known as tag handlers, and require a
descriptor file. This is the classic approach, starting from JSP 1.0.
Tag handlers implement the Tag or BodyTag interfaces, and can be derived from
TagSupport and BodyTagSupport. All of these are in the javax.servlet.jsp.tagext package.
Typical methods to be implemented:

 doStartTag - called when the start tag is encountered


 doEndTag - called when the end tag is encountered
 doInitBody - called before the body is evaluated
 doAfterBody - called after the body is evaluated
 set/get attribute - called to pass in attribute values

The descriptor file


The descriptor is a .tld file, in XML format. It starts with the xml declaration and doctype:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" “http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
...
</taglib>
The following elements are permitted as children of <taglib>:

© Aptech Ltd Version 1.0 103 of 194


Web Component Development Using Java References

tlib-version The version of the library

jsp-version The JSP version targeted

short-name optinal name

uri A URI that uniquely identifies the library

display-name optional name

small-icon optional icon

large-icon optional icon

description optional description

listener Defines a listener; includes a nested listener-class element

tag Defines a tag (see below)

The <tag> element has the following child elements:

name The tag name

tag-class Fully qualified name of the implementation class

tei-class Fully qualified name of the TagExtraInfo class, used to


define scripting variables that are exported to the calling
JSP. This is not needed if there are no exported scripting
variables. Furthermore, the <variable> element can be
used instead.

body-content The body content type: 'empty', 'JSP' or 'tagdependent'

display-name Optional display name

small-icon Optional small icon

large-icon Optional large icon

description Optional description

variable Defines an exported scripting variable (see below)

attribute Defines an attribute (see below)

© Aptech Ltd Version 1.0 104 of 194


Web Component Development Using Java References

The variable element defines an exported scripting variable and has the following attributes:

name-given The name of the variable

name-from- The name of the attribute whose value will define the name of the
attribute variable. Exactly one of name-given and name-from-attribute must
be supplied.

variable-class The class of the variable. The default is java.lang.String.

declare Whether the variable refers to a new object. The default is true.

scope The scope of the variable: NESTED, AT_BEGIN, AT_END.

Finally, the <attribute> element has the following child elements:

name The name of the attribute

required Whether the attribute is required or not: 'true', 'false', 'yes' or 'no'

rtexprvalue Whether a runtime expression is accepted: 'true', 'false', 'yes' or 'no'

type The fully-qualified type of the variable

Simple Tags
Simple tags have no attributes, do not evaluate their bodies, and export no scripting
variables. They are used like this:
<asitl:now/>
The JSP file, test-simple.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
It is now <asitl:now/>
</body>
</html>
The output:
It is now Mon May 02 10:12:02 GMT-05:00 2005
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>

© Aptech Ltd Version 1.0 105 of 194


Web Component Development Using Java References

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library


1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
<tag>
<name>now</name>
<tag-class>net.alethis.tags.CurrentDateTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
The Java class, CurrentDateTag.java:
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class CurrentDateTag extends TagSupport {


public int doStartTag() throws JspException {
try {
Date d = new Date();
pageContext.getOut().print(d.toString());
}
catch (Exception e) {
throw new JspTagException("error in CurrentDateTag: " +
e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure:
test-simple.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
CurrentDateTag.class

© Aptech Ltd Version 1.0 106 of 194


Web Component Development Using Java References

Tags with Attributes


The attributes are received in the tag class via setter methods.
The JSP file, test-attributes.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<html3
<head>
<title>JSP Tag Test</title>
</head>
<body>
<c:set var="x" value="38"/>
The square of ${x} is <asitl:power exponent="2" value="${x}"/>
<br>
The cube of ${x} is <asitl:power exponent="3" value="${x}"/>
</body>
</html>
We're using the JSTL to set up the variable x.
And the output:
The square of 38 is 1444
The cube of 38 is 54872
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>power</name>
<tag-class>net.alethis.tags.PowerTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>exponent</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

© Aptech Ltd Version 1.0 107 of 194


Web Component Development Using Java References

</taglib>
The implementation class, PowerTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PowerTag extends TagSupport {


private String exponentString;
private String valueString;
public void setExponent(String s) {
exponentString = s;
}
public void setValue(String s) {
valueString = s;
}
public int doStartTag() throws JspException {
try {
int exp = Integer.parseInt(exponentString);
int val = Integer.parseInt(valueString);
int result = 1;
for (int i = 0; i < exp; i++) {
result = result * val;
}
pageContext.getOut().print(result);
}
catch (Exception e) {
throw new JspTagException("error in PowerTag: " + e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
Note that the tag only works for positive exponents!
The jar file structure (including the necessary JSTL files):
test-attributes.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
CurrentDateTag.class

© Aptech Ltd Version 1.0 108 of 194


Web Component Development Using Java References

lib
jstl.jar
standard.jar

Tags with Bodies


The techniques to be used depend on what is to be done with the body.
The first distinction is whether the tag 'interacts' with the body. Interaction is required if the
tag needs to read or modify the body content.
A second distinction is whether the tag implements some kind of iteration, where the body
content is evaluated multiple times.
The body-content element in the descriptor file should be set to 'tagdependent' if the body
is plain template text, or 'JSP' if it includes expressions, jsp tags or custom tags.
The general possibilities are:

No interaction, Implement Tag, or inherit from TagSupport; the doStartTag()


no iteration method should return EVAL_BODY_INCLUDE

No interaction, Implement IterationTag, or inherit from TagSupport; doStartTag()


with iteration should return EVAL_BODY_INCLUDE (or SKIP_BODY) and
doAfterBody() should return EVAL_BODY_AGAIN as long as further
iterations are required, and SKIP_BODY at the end.

Interaction, no Implement BodyTag, or inherit from BodyTagSupport; implement


iteration doInitBody() and doAfterBody(); the doStartTag() method should
return EVAL_BODY_BUFFERED

Interaction Implement BodyTag, or inherit from BodyTagSupport; implement


and iteration doInitBody() and doAfterBody(); thedoStartTag() and doAfterBody()
should return EVAL_BODY_AGAIN as long as further iterations are
required, and SKIP_BODY at the end.
To summarize, doStartTag() should return:

 SKIP_BODY - if the body does not need to be evaluated


 EVAL_BODY_INCLUDE - if the body is to be included, but not read or modified by the
tag (the container will not make the BodyContent object available)
 EVAL_BODY_BUFFERED - if the body is to be read or modified; in this case the
container will call setBodyContent() on the tag to initialize the bodyContent; this
method is available only in the BodyTag interface, so it is an error to return this
value from a tag that only implements Tag

Including the Body


This example conditionally includes the body depending on the value of an attribute.
The JSP file, test-include-body.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<html3
<head>
<title>JSP Tag Test</title>

© Aptech Ltd Version 1.0 109 of 194


Web Component Development Using Java References

</head>
<body>
<c:set var="x" value="38"/>
<asitl:ifpositive value="${x}">
First number is positive
</asitl:ifpositive>
<c:set var="x" value="-38"/>
<asitl:ifpositive value="${x}">
Second number is positive
</asitl:ifpositive>
</body>
</html>
The output:
First number is positive
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>ifpositive</name>
<tag-class>net.alethis.tags.IfPositiveTag</tag-class>
<body-content>tagdependent</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The implementation class, PowerTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class IfPositiveTag extends TagSupport {


private String valueString;
public void setValue(String s) {
valueString = s;

© Aptech Ltd Version 1.0 110 of 194


Web Component Development Using Java References

}
public int doStartTag() throws JspException {
try {
int val = Integer.parseInt(valueString);
if (val < 0) {
return SKIP_BODY;
}
else {
return EVAL_BODY_INCLUDE;
}
}
catch (Exception e) {
throw new JspTagException("error in IfPositiveTag: " +
e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure (including the necessary JSTL files):
test-include-body.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
IfPositiveTag.class
lib
jstl.jar
standard.jar

Repeating the Body


This example repeats a body a specified number of times.
The JSP file, test-iterate.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html3
<head>
<title>JSP Tag Test</title>
</head>
<body>
And the answer is<asitl:repeat count="17">.</asitl:repeat> 42!
</body>
</html>

© Aptech Ltd Version 1.0 111 of 194


Web Component Development Using Java References

The output:
And the answer is................. 42!
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>repeat</name>
<tag-class>net.alethis.tags.RepeatTag</tag-class>
<body-content>tagdependent</body-content>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The implementation class, RepeatTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class RepeatTag extends TagSupport {


private String countString;
private int count;
public void setCount(String s) {
countString = s;
}
public int doStartTag() throws JspException {
try {
count = Integer.parseInt(countString);
if (count > 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}

© Aptech Ltd Version 1.0 112 of 194


Web Component Development Using Java References

catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
public int doAfterBody() {
count--;
if (count > 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure (including the necessary JSTL files):
test-iterate.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
RepeatTag.class

Reading the Body


This example shows a tag that reads its body, and replaces the body text with generated
text. Tags of this nature must implement BodyTag, or inherit from BodyTagSupport.
The content of the body is accessible in doAfterBody via the getBodyContent method, which
returns a BodyContent object. The getString() method on this object gets the content. To
write to the output stream, use the JspWriter obtained by calling getEnclosingWriter on the
BodyContent object. This ensures that the content will be available to enclosing tags.
The JSP file, test-read-body.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
3 * 7 = <asitl:evaluate>3 * 7</asitl:evaluate>
<br>
14 + 8 = <asitl:evaluate>14 + 8</asitl:evaluate>
<br>
723 - 194 = <asitl:evaluate>723 - 194</asitl:evaluate>

© Aptech Ltd Version 1.0 113 of 194


Web Component Development Using Java References

<br>
37 / 4 = <asitl:evaluate>37 / 4</asitl:evaluate>
</body>
</html>
The output:
3 * 7 = 21
14 + 8 = 22
723 - 194 = 529
37 / 4 = 9
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>evaluate</name>
<tag-class>net.alethis.tags.EvaluateTag</tag-class>
<body-content>tagdependent</body-content>
</tag>
</taglib>
The implementation class, EvaluateTag.java. The doStartTag() method must return
EVAL_BODY_BUFFERED in order that the BodyContent object be made available.
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class EvaluateTag extends BodyTagSupport {


public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
public int doAfterBody() throws JspException {
try {
BodyContent bc = getBodyContent();
String expression = bc.getString();
bc.clearBody();

StringTokenizer st = new StringTokenizer(expression);


int first = Integer.parseInt(st.nextToken());

© Aptech Ltd Version 1.0 114 of 194


Web Component Development Using Java References

String op = st.nextToken();
int second = Integer.parseInt(st.nextToken());

int result = 0;
if (op.equals("+")) {
result = first + second;
}
else if (op.equals("-")) {
result = first - second;
}
else if (op.equals("*")) {
result = first * second;
}
else if (op.equals("/")) {
result = first / second;
}

JspWriter out = bc.getEnclosingWriter();


out.print(result);
bodyContent.clearBody();

return SKIP_BODY;
}
catch (Exception e) {
throw new JspTagException("error in EvaluateTag: " +
e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure:
test-read-body.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
EvaluateTag.class

Scripting Variables in the Body


This example shows a tag that evaluates its body iteratively, and provides scripting
variables used in the body. Since we're not actually reading or modifying the body, we can
inherit from TagSupport. The doStartTag() method must return EVAL_BODY_INCLUDE

© Aptech Ltd Version 1.0 115 of 194


Web Component Development Using Java References

rather than EVAL_BODY_BUFFERED to indicate the BodyContent object is not needed;


otherwise, the container attempts to call the method that sets the BodyContent, which is
only defined in the BodyTag interface.
Also, since the scripting variables are used only in the body of the custom tag, the NESTED
scope is appropriate.
The JSP file, test-variable.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:powertable from="1" to="10">
<tr>
<td>${value}</td>
<td>${squared}</td>
<td>${cubed}</td>
</tr>
</asitl:powertable>
</body>
</html>
The output:

Value Square Cube

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

The descriptor file, asitl.tld:


<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>

© Aptech Ltd Version 1.0 116 of 194


Web Component Development Using Java References

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>powertable</name>
<tag-class>net.alethis.tags.PowerTableTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>from</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>to</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<variable>
<name-given>value</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>squared</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>cubed</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
</tag>
</taglib>
The implementation class, PowerTableTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PowerTableTag extends TagSupport {

© Aptech Ltd Version 1.0 117 of 194


Web Component Development Using Java References

private String fromString;


private String toString;
private int from;
private int to;
private int curr;
public void setFrom(String s) {
fromString = s;
}
public void setTo(String s) {
toString = s;
}
public int doStartTag() throws JspException {
try {
pageContext.getOut().println("<table border='1'>");
pageContext.getOut().println("<tr>");
pageContext.getOut().println("<th>Value</th>");
pageContext.getOut().println("<th>Square</th>");
pageContext.getOut().println("<th>Cube</th>");
pageContext.getOut().println("</tr>");
from = Integer.parseInt(fromString);
to = Integer.parseInt(toString);
curr = from;

pageContext.setAttribute("value", String.valueOf(curr));
pageContext.setAttribute("squared", String.valueOf(curr * curr));
pageContext.setAttribute("cubed", String.valueOf(curr * curr *
curr));

return EVAL_BODY_INCLUDE;
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
public int doAfterBody() {
curr++;
if (curr <= to) {
pageContext.setAttribute("value", String.valueOf(curr));
pageContext.setAttribute("squared", String.valueOf(curr * curr));
pageContext.setAttribute("cubed", String.valueOf(curr * curr *
curr));

return EVAL_BODY_AGAIN;
}
else {

© Aptech Ltd Version 1.0 118 of 194


Web Component Development Using Java References

return SKIP_BODY;
}
}
public int doEndTag() throws JspException {
try {
pageContext.getOut().println("</table>");
return EVAL_PAGE;
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
}
The jar file structure:
test-variable.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PowerTableTag.class

Scripting Variables in the Rest of the Page


This example shows a tag that provides a scripting variable for the rest of the page. The
appropriate scope is AT_END.
The JSP file, test-variable2.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:provideBrowser/>
Your browser is ${browser}.
</body>
</html>
The output:
Your browser is Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8b)
Gecko/20050201 Firefox/1.0+.
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>

© Aptech Ltd Version 1.0 119 of 194


Web Component Development Using Java References

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
<tag>
<name>provideBrowser</name>
<tag-class>net.alethis.tags.BrowserTag</tag-class>
<body-content>empty</body-content>
<variable>
<name-given>browser</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>AT_END</scope>
</variable>
</tag>
</taglib>
The implementation class, BrowserTag.java:
package net.alethis.tags;

import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class BrowserTag extends TagSupport {


public int doStartTag() throws JspException {
String browser = ((HttpServletRequest)
pageContext.getRequest()).getHeader("User-Agent");
pageContext.setAttribute("browser", browser);
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}
The jar file structure:
test-variable2.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
BrowserTag.class

Dynamic Attributes
The ability of a tag to handle dynamic attributes was introduced in JSP 2.0. The tag handler
must implement DynamicAttributes, which provides the method setDynamicAttribute(), and

© Aptech Ltd Version 1.0 120 of 194


Web Component Development Using Java References

the tld descriptor file must indicate that the tag accepts dynamic attributes (and must use
the JSP 2.0 DTD!).
The JSP file, test-dynamic.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:mapTable a="1" b="5" c="14" d="42"/>
<br>
<asitl:mapTable vvv="niece" www="daughter" xxx="sister" yyy="mother"
zzz="aunt"/>
<br>
<asitl:mapTable rr="green" gg="blue" bb="red"/>
</body>
</html>
The output:

a 1

b 5

c 14

d 42

vvv niece

www daughter

xxx sister

yyy mother

zzz aunt

rr green

gg blue

bb red

The descriptor file, asitl.tld. Note that it uses the JSP 2.0 format. In particular, for
validation, an XML Schema is used instead of a DTD.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

© Aptech Ltd Version 1.0 121 of 194


Web Component Development Using Java References

xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>mapTable</name>
<tag-class>net.alethis.tags.MapTableTag</tag-class>
<body-content>empty</body-content>
<dynamic-attributes>true</dynamic-attributes>
</tag>
</taglib>
The implementation class, MapTableTag.java:
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class MapTableTag extends TagSupport implements DynamicAttributes {


private List names = new ArrayList();
private List values = new ArrayList();
public void setDynamicAttribute(String ns, String name, Object value) {
names.add(name);
values.add(value);
}
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
out.println("<table border='1'>");
for (int i = 0; i < names.size(); i++) {
out.print("<tr>");
out.print("<td>");
out.print((String) names.get(i));
out.println("</td>");
out.print("<td>");
out.print(values.get(i).toString());
out.println("</td>");
out.print("</tr>");
}
out.println("</table>");
return SKIP_BODY;

© Aptech Ltd Version 1.0 122 of 194


Web Component Development Using Java References

}
catch (Exception e) {
throw new JspTagException("error in MapTableTag: " +
e.getMessage());
}
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}
The jar file structure:
test-dynamic.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
MapTableTag.class

Cooperating Tags
Custom tags in a hierarchy can cooperate with each other. The basic mechanism is for a
child tag implementation to access the implementation of a parent tag, or indeed, of any
ancestor tag. TagSupport includes getParent() and setParent() methods that are used to
traverse the hierarchy, and it also includes findAncestorWithClass(), to search for an
arbitary ancestor by class. This is the method used in the following example.
The JSP file, test-wall.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Test Tag</title>
</head>
<body>
<asitl:wall start='10'>
<asitl:bottle/>
<br>
</asitl:wall>
</body>
</html>
The output:
10 bottles of beer on the wall
9 bottles of beer on the wall
8 bottles of beer on the wall
7 bottles of beer on the wall
6 bottles of beer on the wall
5 bottles of beer on the wall

© Aptech Ltd Version 1.0 123 of 194


Web Component Development Using Java References

4 bottles of beer on the wall


3 bottles of beer on the wall
2 bottles of beer on the wall
1 bottles of beer on the wall
0 bottles of beer on the wall
The descriptor file, asitl.tld.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>wall</name>
<tag-class>net.alethis.tags.WallTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>start</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>bottle</name>
<tag-class>net.alethis.tags.BottleTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
The first implementation class, WallTag.java. It iterates the body from the start count down
to zero:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class WallTag extends TagSupport {


private String startString;
private int curr;
public void setStart(String s) {
startString = s;

© Aptech Ltd Version 1.0 124 of 194


Web Component Development Using Java References

}
public int getCurrentCount() {
return curr;
}
public int doStartTag() throws JspException {
try {
curr = Integer.parseInt(startString);
if (curr > 0) {
return EVAL_BODY_INCLUDE;
}
else {
return SKIP_BODY;
}
}
catch (Exception e) {
throw new JspTagException("error in WallTag: " + e.getMessage());
}
}
public int doAfterBody() {
curr--;
if (curr >= 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The second implementation class, BottleTag.java. It accesses the wall tag in order to
determine the current count of the number of bottles left on the wall.
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class BottleTag extends TagSupport {


public int doStartTag() throws JspException {
try {
WallTag wall = (WallTag) findAncestorWithClass(this, WallTag.class);
int curr = wall.getCurrentCount();
pageContext.getOut().println(curr + " bottles of beer on the wall");
return SKIP_BODY;

© Aptech Ltd Version 1.0 125 of 194


Web Component Development Using Java References

}
catch (Exception e) {
throw new JspTagException("error in BottleTag: " + e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure:
test-wall.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
BottleTag.class
WallTag.class

JSP 2.0 Tag Files


With JSP 2.0, two new mechanisms were introduced to simplify the creation of custom tags.
The first of these is known as 'tag files', which implement custom tags by means of files
which look very much like JSP pages. They have the .tag or .tagx extension (classic style
vs. XML style), and included fragments have a .tagf extension. This mechanism is
particularly useful for tags which include a lot of template text.
The files should be placed under WEB-INF/tags.
Implicit objects available:

 request
 response
 session
 application
 out
 config
 jspContext

jspContext replaces pageContext to reduce dependency on Java.


Example: simple tag with no body or attributes:
<%@ tag import="java.util.*" import="java.text.*" %>
<%
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
Date d = new Date(System.currentTimeMillis());
out.println(df.format(d));
%>
Store this as currDate.tag in WEB-INF/tags, and the <currDate> tag becomes available.
Here's a typical JSP file:

© Aptech Ltd Version 1.0 126 of 194


Web Component Development Using Java References

<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>


<html>
<head>
</head>
<body>
Today is <util:currDate/>.
</body>
</html>

Directives
Directives available in tag files:

tag similar to the page directive for JSP pages

include includes other tag files

taglib use another custom tag library

attribute declare an attribute

variable define a scripting variable that becomes visible in the JSP page

The tag directive


The tag directive has the following attributes:

body-content describes the treatment of the body: 'empty', 'tagdependent' or


'scriptless'

import imports classes or packages; this attribute can appear multiple


times

pageEncoding as in the page directive

isELIgnored as in the page directive

dynamic- specifies the name of a map that will receive all undeclared
attributes attributes

language the scripting language, must be 'java' currently

display-name for tools - optional - default is the tag file name, minus extension

small-icon for tools

large-icon for tools

description a description of the tag

© Aptech Ltd Version 1.0 127 of 194


Web Component Development Using Java References

example informal description of how the tag is used


There may be multiple tag directives, but only the import attribute can appear multiple
times among the union of all of their attributes.

The include directive


The include directive includes other files. It has a single 'file' attribute.
<%@ include file='commonheader.tagf' %>

The taglib directive


The taglib directive is as for JSP pages.

The attribute directive


The attribute directive declares an attribute that the tag accepts. The attributes of the
attribute directive are:

name the name of the attribute

required true or false

rtexprvalue true or false - indicates whether runtime expressions are accepted; true
is the default

type the value type - default is java.lang.String

fragment true or false - should the value be evaluated by the container (false), or
passed directly to the tag handler (true)

description a description for the attribute


This tag creates a number of copies of a string; save it as WEB-INF/tags/repeater.tag:
<%@ attribute name="count" type="java.lang.Integer" required="true" %>
<%@ attribute name="value" type="java.lang.String" required="true" %>
<%!
private String repeater(Integer count, String s) {
int n = count.intValue();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
%>
<%
out.println(repeater(count, value));
%>
This tag will accept run-time expressions for both attributes, since true is the default for
rtexprvalue. Use the tag like this:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>

© Aptech Ltd Version 1.0 128 of 194


Web Component Development Using Java References

<html>
<head>
</head>
<body>
Let's get some sleep! <util:repeater count='${3 * 10}' value='zzz'/>
</body>
</html>

The variable directive


The variable directive exports a variable to the JSP page. The attributes are:

name-given The variable name that will be available in the calling JSP page.

name-from- Specifies the name of an attribute, whose value is the name of the
attribute variable that will be available in the calling JSP page. Exactly one of
name-given or name-from-attribute must be supplied.

alias A locally scoped variable which will store the variable's value. Used
only with name-from-attribute.

variable-class The class of the variable. Default is java.lang.String.

declare Indicates whether the variable is declared in the calling JSP page or
tag file. Default is true. Not entirely clear what this means!

scope The variable's scope; possible values are AT_BEGIN, AT_END and
NESTED. NESTED is the default.

description A description for the variable.


The variable value is set by using setAttribute() on the jspContext object.
Here's an example, which uses the default NESTED setting for the scope. That means that
the variable values will be available only within the body of the tag. The <doBody> tag at
the end indicates that the tag body should be rendered, and the variable values will be
available then.
<%@ tag import="java.util.*" %>
<%@ attribute name="cityName" required="true" %>
<%@ variable name-given="province" %>
<%@ variable name-given="population" variable-class="java.lang.Integer" %>
<%
if ("Toronto".equals(cityName)) {
jspContext.setAttribute("province", "Ontario");
jspContext.setAttribute("population", new Integer(2553400));
}
else if ("Montreal".equals(cityName)) {
jspContext.setAttribute("province", "Quebec");
jspContext.setAttribute("population", new Integer(2195800));
}

© Aptech Ltd Version 1.0 129 of 194


Web Component Development Using Java References

else {
jspContext.setAttribute("province", "Unknown");
jspContext.setAttribute("population", new Integer(-1));
}
%>
<jsp:doBody/>
And the JSP page:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>
<% pageContext.setAttribute("cityName", "Montreal"); %>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
This is a bit less wordy using JSTL:
<%@ tag import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="cityName" required="true" %>
<%@ variable name-given="province" %>
<%@ variable name-given="population" %>
<c:choose>
<c:when test="cityName eq 'Toronto'>
<c:set var="province" value="Ontario"/>
<c:set var="population" value="2553400"/>
</c:when>
<c:when test="cityName eq 'Montreal'>
<c:set var="province" value="Quebec"/>
<c:set var="population" value="2195800"/>
</c:when>
<c:otherwise>
<c:set var="province" value="Unknown"/>
<c:set var="population" value="-1"/>
</c:otherwise>
</c:choose>
%>
<jsp:doBody/>
and the JSP:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

© Aptech Ltd Version 1.0 130 of 194


Web Component Development Using Java References

<html>
<head>
</head>
<body>
<c:set var="cityName" value="Montreal"/>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
Or let's do it XML! This would be lookup2.tagx:
<?xml version='1.0'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:directive.tag import="java.util.*"/>
<jsp:directive.taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"/>
<jsp:directive.attribute name="cityName" required="true"/>
<jsp:directive.variable name-given="province"/>
<jsp:directive.variable name-given="population"/>
<c:choose>
<c:when test="cityName eq 'Toronto'>
<c:set var="province" value="Ontario"/>
<c:set var="population" value="2553400"/>
</c:when>
<c:when test="cityName eq 'Montreal'>
<c:set var="province" value="Quebec"/>
<c:set var="population" value="2195800"/>
</c:when>
<c:otherwise>
<c:set var="province" value="Unknown"/>
<c:set var="population" value="-1"/>
</c:otherwise>
</c:choose>
</jsp:root>
and the JSP:
<?xml version='1.0'?>
<jsp:root version='2.0'
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:util="urn:jsptagdir:/WEB-INF/tags"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:directive.page contentType="text/html"/>
<html>
<head>

© Aptech Ltd Version 1.0 131 of 194


Web Component Development Using Java References

</head>
<body>
<c:set var="cityName" value="Montreal"/>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
</jsp:root>
The scope is a bit hard to understand. Here are the interpretations:

EVENT NESTED AT_BEGIN AT_END

beginning of tag file save nothing nothing

before any fragment tag to page tag to page nothing

after any fragment nothing nothing nothing

end of tag file restore tag to page tag to page


Save/restore means that the value of the variable from the page is saved on entry to tag
and the restored afterwards. Consequently, any changes made inside the tag are not visible
to the the page. The actions of the tag therefore apply only within the tag, which is suitable
for the NESTED scope.
Tag to page means that the value of the variable inside the tag is copied to the page's copy
of the variable. Consequently, for AT_END scope, the tag sees the initial value of the
variable from the page, and then exports the value back to the page at the end. For the
AT_BEGIN scope, the tag observes an uninitialized value for the variable, and exports it
back to the page at the end.
Is that any clearer?

Dynamic attributes
The tag directive can include a dynamic-attributes attribute, which gives the name of a map
which stores all of the tag attributes which are not explicitly declared. Here's an example of
how it can be used. First, the tag file (tabular.tag), which shows how to receive the
attributes via Java and using JSTL and expressions:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ tag import="java.util.*" %>
<%@ tag dynamic-attributes="attributes" %>
<%@ attribute name="title" %>

<%
out.println(jspContext.getAttribute("title"));
out.println("<table border='1'>");
Map m = (Map) jspContext.getAttribute("attributes");
for (Iterator i = m.keySet().iterator(); i.hasNext(); ) {

© Aptech Ltd Version 1.0 132 of 194


Web Component Development Using Java References

Object key = i.next();


Object val = m.get(key);
out.println("<tr>");
out.println("<td>" + key + "</td>");
out.println("<td>" + val + "</td>");
out.println("</tr>");
}
out.println("</table>");
%>

${title}
<table border='1'>
<c:forEach var="item" items="${attributes}">
<tr><td>${item.key}</td><td>${item.value}</td></tr>
</c:forEach>
</table>
And the jsp page:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>
<util:tabular title="Dynamic Attributes!" name="Fred" wife="Wilma"
friend="Barney" lover="Betty"/>
</body>
</html>
Which produces two copies of the following:
Dynamic Attributes!

wife Wilma

friend Barney

name Fred

lover Betty

JSP 2.0 Tags


Introduction
The second new mechanism in JSP 2.0 is a simplified approach to writing tags using Java
classes. It's based on the 'SimpleTag' interface, which is not even in the same class
hierarchy as the tag classes from JSP 1.0. It also uses the 'JspFragment' class to represent
sections of a JSP page. The implementation of tag files uses the JSP 2.0 tag approach; a JSP
2.0 tag is generated from the tag file.

The JSP 1.0 approach is similar to event-driven programming - the JSP code reacts to tag
start, end and body events. The JSP 2.0 approach is more top-down: the tag class has a

© Aptech Ltd Version 1.0 133 of 194


Web Component Development Using Java References

single method, doTag(), which is called when the tag is encountered, and the body is
presented to the tag class as a JspFragment.
To evaluate the body, the JspFragment class provides an invoke() method. For iterating
over the body, the tag class just calls invoke() in a loop. invoke() takes a writer as
parameter; you can supply a writer if you want to capture the output, or pass null to have it
write to the default stream.
Here's the SimpleTag interface:
public interface SimpleTag extends JspTag {
public void doTag()throws JspException, java.io.IOException;
public void setParent(JspTag parent);
public JspTag getParent();
public void setJspContext(JspContext pc);
public void setJspBody(JspFragment jspBody);
}
JspTag was introduced in 2.0 as a base interface for Tag and SimpleTag. It defines no
methods.
When implementing a simple tag, one typically derives from SimpleTagSupport. It provides
getJspBody() and findAncestorWithClass() methods.
When the doTag() method is called, setters for all attributes, and the setJspBody() method
(if necessary) will have been called. The entire processing of the tag therefore takes place in
doTag().
The JspContext object replaces the page context object used in JSP 1.0 tags. The idea is
that this object is not dependent on http servlet classes, making the approach more generic.
The body is available to the tag as a JspFragment, but it is also possible to define attributes
as fragments. In this case the setter method must accept a JspFrament object, and the
attribute must be declared as a fragment in the descriptor file. This approach is useful when
the tag needs to display different template text depending on runtime conditions.

Example
Here's a rather complicated example. The idea is to build a table of primes, where the
background color of each row indicates whether the prime is even, or of the forms 4k+1 or
4k+3. This is interesting (to some), since Fermat proved that all primes of the form 4k+1
can be written as the sum of two squares, while all primes of the form 4k+3 cannot be so
written. That's interesting, isn't it? The JSP page, test-fragment.jsp, appears below. Note
how all of the template text that builds the table is contained in the JSP page. The
conditional parts, which define the background color of the row, depending on the prime in
question, appear as attributes of the custom tag.
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Test Tag</title>
</head>
<body>
<asitl:primes>
<jsp:attribute name="count">
10
</jsp:attribute>
<jsp:attribute name="evens">

© Aptech Ltd Version 1.0 134 of 194


Web Component Development Using Java References

<tr bgcolor='lightgreen'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:attribute name="odds1">
<tr bgcolor='cyan'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:attribute name="odds3">
<tr bgcolor='pink'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:body>
<table border='1' cellpadding='3'>
<tr><th>Position</th><th>Prime</th><tr>
${content}
</table>
</jsp:body>
</asitl:primes>
</body>
</html>
The output:

Position Prime

1 2

2 3

3 5

4 7

5 11

6 13

7 17

8 19

9 23

10 29

The descriptor file:


<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

© Aptech Ltd Version 1.0 135 of 194


Web Component Development Using Java References

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>primes</name>
<tag-class>net.alethis.tags.PrimesTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>evens</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<attribute>
<name>odds1</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<attribute>
<name>odds3</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<variable>
<name-given>index</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>value</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>

© Aptech Ltd Version 1.0 136 of 194


Web Component Development Using Java References

<name-given>content</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
</tag>
</taglib>
The implementation class, PrimesTag.java. Note how the output from the attribute
fragments is captured, while the output from the body fragment is just sent to the standard
output writer.
package net.alethis.tags;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PrimesTag extends SimpleTagSupport {


private String countString;
private JspFragment evensFragment;
private JspFragment odds1Fragment;
private JspFragment odds3Fragment;
public void setCount(String s) {
countString = s;
}
public void setEvens(JspFragment f) {
evensFragment = f;
}
public void setOdds1(JspFragment f) {
odds1Fragment = f;
}
public void setOdds3(JspFragment f) {
odds3Fragment = f;
}
public void doTag() throws JspException {
try {
int count = Integer.parseInt(countString);
StringWriter sw = new StringWriter();
int lastPrime = 0;
int total = 0;
for (int i = 1; total < count; i++) {
int p = nextPrime(lastPrime);
total++;
getJspContext().setAttribute("index", String.valueOf(total));
getJspContext().setAttribute("value", String.valueOf(p));
if (p % 2 == 0) {

© Aptech Ltd Version 1.0 137 of 194


Web Component Development Using Java References

evensFragment.invoke(sw);
}
else if (p % 4 == 1) {
odds1Fragment.invoke(sw);
}
else if (p % 4 == 3) {
odds3Fragment.invoke(sw);
}
lastPrime = p;
}
getJspContext().setAttribute("content", sw.toString());
getJspBody().invoke(null);
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
private int nextPrime(int start) {
for (int k = start + 1; ; k++) {
if (k < 2) {
continue;
}
boolean isPrime = true;
int sqrt = (int) Math.sqrt(k);
for (int m = 2; m <= sqrt; m++) {
if (k % m == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
return k;
}
}
}
}
The war file structure:
test-primes.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PrimesTag.class

© Aptech Ltd Version 1.0 138 of 194


Web Component Development Using Java References

These tags are implemented via Java classes, known as tag handlers, and require a
descriptor file. This is the classic approach, starting from JSP 1.0.

Tag handlers implement the Tag or BodyTag interfaces, and can be derived from
TagSupport and BodyTagSupport. All of these are in the javax.servlet.jsp.tagext package.
Typical methods to be implemented:

 doStartTag - called when the start tag is encountered

 doEndTag - called when the end tag is encountered

 doInitBody - called before the body is evaluated

 doAfterBody - called after the body is evaluated

 release - ???

 set/get attribute - called to pass in attribute values

The descriptor file

The descriptor is a .tld file, in XML format. It starts with the xml declaration and doctype:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
...
</taglib>

The following elements are permitted as children of <taglib>:

 tlib-version The version of the library

 jsp-version The JSP version targeted

 short-name optinal name

 uri A URI that uniquely identifies the library


 display-name optional name

 small-icon optional icon

 large-icon optional icon

 description optional description

 listener Defines a listener; includes a nested listener-class element

 tag Defines a tag (see below)

The <tag> element has the following child elements:

 name The tag name

© Aptech Ltd Version 1.0 139 of 194


Web Component Development Using Java References

 tag-class Fully qualified name of the implementation class

 tei-class Fully qualified name of the TagExtraInfo class, used to define scripting
variables that are exported to the calling JSP. This is not needed if there are no
exported scripting variables. Furthermore, the <variable> element can be used
instead.

 body-content The body content type: 'empty', 'JSP' or 'tagdependent'

 display-name Optional display name

 small-icon Optional small icon


 large-icon Optional large icon

 description Optional description

 variable Defines an exported scripting variable (see below)

 attribute Defines an attribute (see below)


The variable element defines an exported scripting variable and has the following attributes:

 name-given The name of the variable

 name-from-attribute The name of the attribute whose value will define the name of
the variable. Exactly one of name-given and name-from-attribute must be supplied.

 variable-class The class of the variable. The default is java.lang.String.

 declare Whether the variable refers to a new object. The default is true.

 scope The scope of the variable: NESTED, AT_BEGIN, AT_END.

 Finally, the <attribute> element has the following child elements:

 name The name of the attribute

 required Whether the attribute is required or not: 'true', 'false', 'yes' or 'no'

 rtexprvalue Whether a runtime expression is accepted: 'true', 'false', 'yes' or 'no'

 type The fully-qualified type of the variable

Simple Tags

Simple tags have no attributes, do not evaluate their bodies, and export no scripting
variables. They are used like this:
<asitl:now/>
The JSP file, test-simple.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>

© Aptech Ltd Version 1.0 140 of 194


Web Component Development Using Java References

</head>
<body>
It is now <asitl:now/>
</body>
</html>
The output:
It is now Mon May 02 10:12:02 GMT-05:00 2005
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
<tag>
<name>now</name>
<tag-class>net.alethis.tags.CurrentDateTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
The Java class, CurrentDateTag.java:
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class CurrentDateTag extends TagSupport {


public int doStartTag() throws JspException {
try {
Date d = new Date();
pageContext.getOut().print(d.toString());

© Aptech Ltd Version 1.0 141 of 194


Web Component Development Using Java References

}
catch (Exception e) {
throw new JspTagException("error in CurrentDateTag: " +
e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}

The jar file structure:


test-simple.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
CurrentDateTag.class

Tags with Attributes

The attributes are received in the tag class via setter methods.

The JSP file, test-attributes.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<html3
<head>
<title>JSP Tag Test</title>
</head>
<body>
<c:set var="x" value="38"/>
The square of ${x} is <asitl:power exponent="2" value="${x}"/>
<br>

© Aptech Ltd Version 1.0 142 of 194


Web Component Development Using Java References

The cube of ${x} is <asitl:power exponent="3" value="${x}"/>


</body>
</html>
We're using the JSTL to set up the variable x.
And the output:
The square of 38 is 1444
The cube of 38 is 54872
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>power</name>
<tag-class>net.alethis.tags.PowerTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>exponent</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The implementation class, PowerTag.java:
package net.alethis.tags;

© Aptech Ltd Version 1.0 143 of 194


Web Component Development Using Java References

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PowerTag extends TagSupport {


private String exponentString;
private String valueString;
public void setExponent(String s) {
exponentString = s;
}
public void setValue(String s) {
valueString = s;
}
public int doStartTag() throws JspException {
try {
int exp = Integer.parseInt(exponentString);
int val = Integer.parseInt(valueString);
int result = 1;
for (int i = 0; i < exp; i++) {
result = result * val;
}
pageContext.getOut().print(result);
}
catch (Exception e) {
throw new JspTagException("error in PowerTag: " + e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}

Note that the tag only works for positive exponents!

The jar file structure (including the necessary JSTL files):

test-attributes.jsp

© Aptech Ltd Version 1.0 144 of 194


Web Component Development Using Java References

WEB-INF
asitl.tld
classes
net
alethis
tags
CurrentDateTag.class
lib
jstl.jar
standard.jar

Tags with Bodies

The techniques to be used depend on what is to be done with the body.

The first distinction is whether the tag 'interacts' with the body. Interaction is required if the
tag needs to read or modify the body content.

A second distinction is whether the tag implements some kind of iteration, where the body
content is evaluated multiple times.

The body-content element in the descriptor file should be set to 'tagdependent' if the body
is plain template text, or 'JSP' if it includes expressions, jsp tags or custom tags.

The general possibilities are:

No interaction, no iteration Implement Tag, or inherit from TagSupport; the doStartTag()


method should return EVAL_BODY_INCLUDE

No interaction, with iteration Implement IterationTag, or inherit from TagSupport;


doStartTag() should return EVAL_BODY_INCLUDE (or SKIP_BODY) and doAfterBody()
should return EVAL_BODY_AGAIN as long as further iterations are required, and SKIP_BODY
at the end.

Interaction, no iteration Implement BodyTag, or inherit from BodyTagSupport;


implement doInitBody() and doAfterBody(); the doStartTag() method should return
EVAL_BODY_BUFFERED

Interaction and iteration Implement BodyTag, or inherit from BodyTagSupport;


implement doInitBody() and doAfterBody(); thedoStartTag() and doAfterBody() should
return EVAL_BODY_AGAIN as long as further iterations are required, and SKIP_BODY at the
end.

To summarize, doStartTag() should return:

SKIP_BODY - if the body does not need to be evaluated

© Aptech Ltd Version 1.0 145 of 194


Web Component Development Using Java References

EVAL_BODY_INCLUDE - if the body is to be included, but not read or modified by the tag
(the container will not make the BodyContent object available)

EVAL_BODY_BUFFERED - if the body is to be read or modified; in this case the container will
call setBodyContent() on the tag to initialize the bodyContent; this method is available only
in the BodyTag interface, so it is an error to return this value from a tag that only
implements Tag

Including the Body

This example conditionally includes the body depending on the value of an attribute.

The JSP file, test-include-body.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<html3
<head>
<title>JSP Tag Test</title>
</head>
<body>
<c:set var="x" value="38"/>
<asitl:ifpositive value="${x}">
First number is positive
</asitl:ifpositive>
<c:set var="x" value="-38"/>
<asitl:ifpositive value="${x}">
Second number is positive
</asitl:ifpositive>
</body>
</html>
The output:
First number is positive
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

© Aptech Ltd Version 1.0 146 of 194


Web Component Development Using Java References

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>ifpositive</name>
<tag-class>net.alethis.tags.IfPositiveTag</tag-class>
<body-content>tagdependent</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The implementation class, PowerTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class IfPositiveTag extends TagSupport {


private String valueString;
public void setValue(String s) {
valueString = s;
}
public int doStartTag() throws JspException {
try {
int val = Integer.parseInt(valueString);
if (val < 0) {
return SKIP_BODY;
}
else {

© Aptech Ltd Version 1.0 147 of 194


Web Component Development Using Java References

return EVAL_BODY_INCLUDE;
}
}
catch (Exception e) {
throw new JspTagException("error in IfPositiveTag: " +
e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The jar file structure (including the necessary JSTL files):
test-include-body.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
IfPositiveTag.class
lib
jstl.jar
standard.jar
Repeating the Body

This example repeats a body a specified number of times.

The JSP file, test-iterate.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html3
<head>
<title>JSP Tag Test</title>
</head>
<body>

© Aptech Ltd Version 1.0 148 of 194


Web Component Development Using Java References

And the answer is<asitl:repeat count="17">.</asitl:repeat> 42!


</body>
</html>
The output:
And the answer is................. 42!
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>repeat</name>
<tag-class>net.alethis.tags.RepeatTag</tag-class>
<body-content>tagdependent</body-content>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
The implementation class, RepeatTag.java:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class RepeatTag extends TagSupport {


private String countString;

© Aptech Ltd Version 1.0 149 of 194


Web Component Development Using Java References

private int count;


public void setCount(String s) {
countString = s;
}
public int doStartTag() throws JspException {
try {
count = Integer.parseInt(countString);
if (count > 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
public int doAfterBody() {
count--;
if (count > 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}

The jar file structure (including the necessary JSTL files):

© Aptech Ltd Version 1.0 150 of 194


Web Component Development Using Java References

test-iterate.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
RepeatTag.class

Reading the Body

This example shows a tag that reads its body, and replaces the body text with generated
text. Tags of this nature must implement BodyTag, or inherit from BodyTagSupport.
The content of the body is accessible in doAfterBody via the getBodyContent method, which
returns a BodyContent object. The getString() method on this object gets the content. To
write to the output stream, use the JspWriter obtained by calling getEnclosingWriter on the
BodyContent object. This ensures that the content will be available to enclosing tags.

The JSP file, test-read-body.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
3 * 7 = <asitl:evaluate>3 * 7</asitl:evaluate>
<br>
14 + 8 = <asitl:evaluate>14 + 8</asitl:evaluate>
<br>
723 - 194 = <asitl:evaluate>723 - 194</asitl:evaluate>
<br>
37 / 4 = <asitl:evaluate>37 / 4</asitl:evaluate>
</body>
</html>
The output:
3 * 7 = 21

© Aptech Ltd Version 1.0 151 of 194


Web Component Development Using Java References

14 + 8 = 22
723 - 194 = 529
37 / 4 = 9
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>evaluate</name>
<tag-class>net.alethis.tags.EvaluateTag</tag-class>
<body-content>tagdependent</body-content>
</tag>
</taglib>

The implementation class, EvaluateTag.java. The doStartTag() method must return


EVAL_BODY_BUFFERED in order that the BodyContent object be made available.
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class EvaluateTag extends BodyTagSupport {


public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
public int doAfterBody() throws JspException {
try {
BodyContent bc = getBodyContent();
String expression = bc.getString();

© Aptech Ltd Version 1.0 152 of 194


Web Component Development Using Java References

bc.clearBody();

StringTokenizer st = new StringTokenizer(expression);


int first = Integer.parseInt(st.nextToken());
String op = st.nextToken();
int second = Integer.parseInt(st.nextToken());

int result = 0;
if (op.equals("+")) {
result = first + second;
}
else if (op.equals("-")) {
result = first - second;
}
else if (op.equals("*")) {
result = first * second;
}
else if (op.equals("/")) {
result = first / second;
}

JspWriter out = bc.getEnclosingWriter();


out.print(result);
bodyContent.clearBody();

return SKIP_BODY;
}
catch (Exception e) {
throw new JspTagException("error in EvaluateTag: " +
e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;

© Aptech Ltd Version 1.0 153 of 194


Web Component Development Using Java References

}
}

The jar file structure:

test-read-body.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
EvaluateTag.class

Scripting Variables in the Body

This example shows a tag that evaluates its body iteratively, and provides scripting
variables used in the body. Since we're not actually reading or modifying the body, we can
inherit from TagSupport. The doStartTag() method must return EVAL_BODY_INCLUDE
rather than EVAL_BODY_BUFFERED to indicate the BodyContent object is not needed;
otherwise, the container attempts to call the method that sets the BodyContent, which is
only defined in the BodyTag interface.

Also, since the scripting variables are used only in the body of the custom tag, the NESTED
scope is appropriate.

The JSP file, test-variable.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:powertable from="1" to="10">
<tr>
<td>${value}</td>
<td>${squared}</td>
<td>${cubed}</td>
</tr>

© Aptech Ltd Version 1.0 154 of 194


Web Component Development Using Java References

</asitl:powertable>
</body>
</html>
The output:
Value Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>powertable</name>
<tag-class>net.alethis.tags.PowerTableTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>from</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>

© Aptech Ltd Version 1.0 155 of 194


Web Component Development Using Java References

<attribute>
<name>to</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<variable>
<name-given>value</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>squared</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>cubed</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
</tag>
</taglib>

The implementation class, PowerTableTag.java:

package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PowerTableTag extends TagSupport {


private String fromString;
private String toString;

© Aptech Ltd Version 1.0 156 of 194


Web Component Development Using Java References

private int from;


private int to;
private int curr;
public void setFrom(String s) {
fromString = s;
}
public void setTo(String s) {
toString = s;
}
public int doStartTag() throws JspException {
try {
pageContext.getOut().println("<table border='1'>");
pageContext.getOut().println("<tr>");
pageContext.getOut().println("<th>Value</th>");
pageContext.getOut().println("<th>Square</th>");
pageContext.getOut().println("<th>Cube</th>");
pageContext.getOut().println("</tr>");
from = Integer.parseInt(fromString);
to = Integer.parseInt(toString);
curr = from;

pageContext.setAttribute("value", String.valueOf(curr));
pageContext.setAttribute("squared", String.valueOf(curr * curr));
pageContext.setAttribute("cubed", String.valueOf(curr * curr *
curr));

return EVAL_BODY_INCLUDE;
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
public int doAfterBody() {
curr++;

© Aptech Ltd Version 1.0 157 of 194


Web Component Development Using Java References

if (curr <= to) {


pageContext.setAttribute("value", String.valueOf(curr));
pageContext.setAttribute("squared", String.valueOf(curr * curr));
pageContext.setAttribute("cubed", String.valueOf(curr * curr *
curr));

return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
public int doEndTag() throws JspException {
try {
pageContext.getOut().println("</table>");
return EVAL_PAGE;
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
}

The jar file structure:

test-variable.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PowerTableTag.class

© Aptech Ltd Version 1.0 158 of 194


Web Component Development Using Java References

Scripting Variables in the Rest of the Page

This example shows a tag that provides a scripting variable for the rest of the page. The
appropriate scope is AT_END.
The JSP file, test-variable2.jsp:
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:provideBrowser/>
Your browser is ${browser}.
</body>
</html>
The output:
Your browser is Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8b)
Gecko/20050201 Firefox/1.0+.
The descriptor file, asitl.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
<tag>
<name>provideBrowser</name>
<tag-class>net.alethis.tags.BrowserTag</tag-class>
<body-content>empty</body-content>
<variable>
<name-given>browser</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>AT_END</scope>

© Aptech Ltd Version 1.0 159 of 194


Web Component Development Using Java References

</variable>
</tag>
</taglib>
The implementation class, BrowserTag.java:
package net.alethis.tags;

import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class BrowserTag extends TagSupport {


public int doStartTag() throws JspException {
String browser = ((HttpServletRequest)
pageContext.getRequest()).getHeader("User-Agent");
pageContext.setAttribute("browser", browser);
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}

The jar file structure:

test-variable2.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
BrowserTag.class

© Aptech Ltd Version 1.0 160 of 194


Web Component Development Using Java References

Dynamic Attributes

The ability of a tag to handle dynamic attributes was introduced in JSP 2.0. The tag handler
must implement DynamicAttributes, which provides the method setDynamicAttribute(), and
the tld descriptor file must indicate that the tag accepts dynamic attributes (and must use
the JSP 2.0 DTD!).

The JSP file, test-dynamic.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Tag Test</title>
</head>
<body>
<asitl:mapTable a="1" b="5" c="14" d="42"/>
<br>
<asitl:mapTable vvv="niece" www="daughter" xxx="sister" yyy="mother"
zzz="aunt"/>
<br>
<asitl:mapTable rr="green" gg="blue" bb="red"/>
</body>
</html>
The output:
a 1
b 5
c 14
d 42

vvv niece
www daughter
xxx sister
yyy mother
zzz aunt

rr green
gg blue
bb red

© Aptech Ltd Version 1.0 161 of 194


Web Component Development Using Java References

The descriptor file, asitl.tld. Note that it uses the JSP 2.0 format. In particular, for
validation, an XML Schema is used instead of a DTD.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>mapTable</name>
<tag-class>net.alethis.tags.MapTableTag</tag-class>
<body-content>empty</body-content>
<dynamic-attributes>true</dynamic-attributes>
</tag>
</taglib>
The implementation class, MapTableTag.java:
package net.alethis.tags;

import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class MapTableTag extends TagSupport implements DynamicAttributes {


private List names = new ArrayList();
private List values = new ArrayList();
public void setDynamicAttribute(String ns, String name, Object value) {
names.add(name);
values.add(value);
}

© Aptech Ltd Version 1.0 162 of 194


Web Component Development Using Java References

public int doStartTag() throws JspException {


try {
JspWriter out = pageContext.getOut();
out.println("<table border='1'>");
for (int i = 0; i < names.size(); i++) {
out.print("<tr>");
out.print("<td>");
out.print((String) names.get(i));
out.println("</td>");
out.print("<td>");
out.print(values.get(i).toString());
out.println("</td>");
out.print("</tr>");
}
out.println("</table>");
return SKIP_BODY;
}
catch (Exception e) {
throw new JspTagException("error in MapTableTag: " +
e.getMessage());
}
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}

The jar file structure:

test-dynamic.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags

© Aptech Ltd Version 1.0 163 of 194


Web Component Development Using Java References

MapTableTag.class

Cooperating Tags

Custom tags in a hierarchy can cooperate with each other. The basic mechanism is for a
child tag implementation to access the implementation of a parent tag, or indeed, of any
ancestor tag. TagSupport includes getParent() and setParent() methods that are used to
traverse the hierarchy, and it also includes findAncestorWithClass(), to search for an
arbitary ancestor by class. This is the method used in the following example.

The JSP file, test-wall.jsp:


<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Test Tag</title>
</head>
<body>
<asitl:wall start='10'>
<asitl:bottle/>
<br>
</asitl:wall>
</body>
</html>
The output:
10 bottles of beer on the wall
9 bottles of beer on the wall
8 bottles of beer on the wall
7 bottles of beer on the wall
6 bottles of beer on the wall
5 bottles of beer on the wall
4 bottles of beer on the wall
3 bottles of beer on the wall
2 bottles of beer on the wall
1 bottles of beer on the wall
0 bottles of beer on the wall
The descriptor file, asitl.tld.

© Aptech Ltd Version 1.0 164 of 194


Web Component Development Using Java References

<?xml version="1.0" encoding="ISO-8859-1" ?>


<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>wall</name>
<tag-class>net.alethis.tags.WallTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>start</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>bottle</name>
<tag-class>net.alethis.tags.BottleTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

The first implementation class, WallTag.java. It iterates the body from the start count down
to zero:
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

© Aptech Ltd Version 1.0 165 of 194


Web Component Development Using Java References

public class WallTag extends TagSupport {


private String startString;
private int curr;
public void setStart(String s) {
startString = s;
}
public int getCurrentCount() {
return curr;
}
public int doStartTag() throws JspException {
try {
curr = Integer.parseInt(startString);
if (curr > 0) {
return EVAL_BODY_INCLUDE;
}
else {
return SKIP_BODY;
}
}
catch (Exception e) {
throw new JspTagException("error in WallTag: " + e.getMessage());
}
}
public int doAfterBody() {
curr--;
if (curr >= 0) {
return EVAL_BODY_AGAIN;
}
else {
return SKIP_BODY;
}
}
public int doEndTag() {
return EVAL_PAGE;

© Aptech Ltd Version 1.0 166 of 194


Web Component Development Using Java References

}
}

The second implementation class, BottleTag.java. It accesses the wall tag in order to
determine the current count of the number of bottles left on the wall.
package net.alethis.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class BottleTag extends TagSupport {


public int doStartTag() throws JspException {
try {
WallTag wall = (WallTag) findAncestorWithClass(this, WallTag.class);
int curr = wall.getCurrentCount();
pageContext.getOut().println(curr + " bottles of beer on the wall");
return SKIP_BODY;
}
catch (Exception e) {
throw new JspTagException("error in BottleTag: " + e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}

The jar file structure:

test-wall.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
BottleTag.class

© Aptech Ltd Version 1.0 167 of 194


Web Component Development Using Java References

WallTag.class

JSP 2.0 Tag Files

With JSP 2.0, two new mechanisms were introduced to simplify the creation of custom tags.
The first of these is known as 'tag files', which implement custom tags by means of files
which look very much like JSP pages. They have the .tag or .tagx extension (classic style
vs. XML style), and included fragments have a .tagf extension. This mechanism is
particularly useful for tags which include a lot of template text.

The files should be placed under WEB-INF/tags.

Implicit objects available:

 request

 response

 session

 application

 out

 config
 jspContext

jspContext replaces pageContext to reduce dependency on Java.

Example: simple tag with no body or attributes:


<%@ tag import="java.util.*" import="java.text.*" %>
<%
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
Date d = new Date(System.currentTimeMillis());
out.println(df.format(d));
%>
Store this as currDate.tag in WEB-INF/tags, and the <currDate> tag becomes
available. Here's a typical JSP file:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>
Today is <util:currDate/>.
</body>

© Aptech Ltd Version 1.0 168 of 194


Web Component Development Using Java References

</html>

Directives

Directives available in tag files:

 tag similar to the page directive for JSP pages


 include includes other tag files

taglib use another custom tag library

 attribute declare an attribute

 variable define a scripting variable that becomes visible in the JSP page

The tag directive

The tag directive has the following attributes:

 body-content describes the treatment of the body: 'empty', 'tagdependent' or


'scriptless'

 import imports classes or packages; this attribute can appear multiple times

 pageEncoding as in the page directive

 isELIgnored as in the page directive

 dynamic-attributes specifies the name of a map that will receive all undeclared
attributes

 language the scripting language, must be 'java' currently

 display-name for tools - optional - default is the tag file name, minus extension

 small-icon for tools

 large-icon for tools

 description a description of the tag

 example informal description of how the tag is used

There may be multiple tag directives, but only the import attribute can appear multiple
times among the union of all of their attributes.
The include directive

The include directive includes other files. It has a single 'file' attribute.
<%@ include file='commonheader.tagf' %>

The taglib directive

The taglib directive is as for JSP pages.

© Aptech Ltd Version 1.0 169 of 194


Web Component Development Using Java References

The attribute directive

The attribute directive declares an attribute that the tag accepts. The attributes of the
attribute directive are:
 name the name of the attribute

 required true or false

 rtexprvalue true or false - indicates whether runtime expressions are accepted;


true is the default

 type the value type - default is java.lang.String


 fragment true or false - should the value be evaluated by the container (false),
or passed directly to the tag handler (true)

 description a description for the attribute

This tag creates a number of copies of a string; save it as WEB-INF/tags/repeater.tag:


<%@ attribute name="count" type="java.lang.Integer" required="true" %>
<%@ attribute name="value" type="java.lang.String" required="true" %>
<%!
private String repeater(Integer count, String s) {
int n = count.intValue();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
%>
<%
out.println(repeater(count, value));
%>
This tag will accept run-time expressions for both attributes, since true is
the default for rtexprvalue. Use the tag like this:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>

© Aptech Ltd Version 1.0 170 of 194


Web Component Development Using Java References

Let's get some sleep! <util:repeater count='${3 * 10}' value='zzz'/>


</body>
</html>

The variable directive

The variable directive exports a variable to the JSP page. The attributes are:

 name-given The variable name that will be available in the calling JSP page.

 name-from-attribute Specifies the name of an attribute, whose value is the name of


the variable that will be available in the calling JSP page. Exactly one of name-given
or name-from-attribute must be supplied.

 alias A locally scoped variable which will store the variable's value. Used only with
name-from-attribute.

 variable-class The class of the variable. Default is java.lang.String.


 declare Indicates whether the variable is declared in the calling JSP page or
tag file. Default is true. Not entirely clear what this means!

 scope The variable's scope; possible values are AT_BEGIN, AT_END and NESTED.
NESTED is the default.

 description A description for the variable.

The variable value is set by using setAttribute() on the jspContext object.

Here's an example, which uses the default NESTED setting for the scope. That means that
the variable values will be available only within the body of the tag. The <doBody> tag at
the end indicates that the tag body should be rendered, and the variable values will be
available then.
<%@ tag import="java.util.*" %>
<%@ attribute name="cityName" required="true" %>
<%@ variable name-given="province" %>
<%@ variable name-given="population" variable-class="java.lang.Integer" %>
<%
if ("Toronto".equals(cityName)) {
jspContext.setAttribute("province", "Ontario");
jspContext.setAttribute("population", new Integer(2553400));
}
else if ("Montreal".equals(cityName)) {
jspContext.setAttribute("province", "Quebec");

© Aptech Ltd Version 1.0 171 of 194


Web Component Development Using Java References

jspContext.setAttribute("population", new Integer(2195800));


}
else {
jspContext.setAttribute("province", "Unknown");
jspContext.setAttribute("population", new Integer(-1));
}
%>
<jsp:doBody/>
And the JSP page:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>
<% pageContext.setAttribute("cityName", "Montreal"); %>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
This is a bit less wordy using JSTL:
<%@ tag import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="cityName" required="true" %>
<%@ variable name-given="province" %>
<%@ variable name-given="population" %>
<c:choose>
<c:when test="cityName eq 'Toronto'>
<c:set var="province" value="Ontario"/>
<c:set var="population" value="2553400"/>
</c:when>
<c:when test="cityName eq 'Montreal'>

© Aptech Ltd Version 1.0 172 of 194


Web Component Development Using Java References

<c:set var="province" value="Quebec"/>


<c:set var="population" value="2195800"/>
</c:when>
<c:otherwise>
<c:set var="province" value="Unknown"/>
<c:set var="population" value="-1"/>
</c:otherwise>
</c:choose>
%>
<jsp:doBody/>
and the JSP:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>
<body>
<c:set var="cityName" value="Montreal"/>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
Or let's do it XML! This would be lookup2.tagx:
<?xml version='1.0'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:directive.tag import="java.util.*"/>
<jsp:directive.taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"/>
<jsp:directive.attribute name="cityName" required="true"/>
<jsp:directive.variable name-given="province"/>
<jsp:directive.variable name-given="population"/>
<c:choose>

© Aptech Ltd Version 1.0 173 of 194


Web Component Development Using Java References

<c:when test="cityName eq 'Toronto'>


<c:set var="province" value="Ontario"/>
<c:set var="population" value="2553400"/>
</c:when>
<c:when test="cityName eq 'Montreal'>
<c:set var="province" value="Quebec"/>
<c:set var="population" value="2195800"/>
</c:when>
<c:otherwise>
<c:set var="province" value="Unknown"/>
<c:set var="population" value="-1"/>
</c:otherwise>
</c:choose>
</jsp:root>
and the JSP:
<?xml version='1.0'?>
<jsp:root version='2.0'
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:util="urn:jsptagdir:/WEB-INF/tags"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:directive.page contentType="text/html"/>
<html>
<head>
</head>
<body>
<c:set var="cityName" value="Montreal"/>
<util:lookup cityName="${cityName}">
${cityName}'s province is ${province}.
${cityName}'s population is approximately ${population / 1000000}
million.
</util:lookup>
</body>
</html>
</jsp:root>

© Aptech Ltd Version 1.0 174 of 194


Web Component Development Using Java References

The scope is a bit hard to understand. Here are the interpretations:

EVENT NESTED AT_BEGIN AT_END

beginning of tag file save nothing nothing

before any fragment tag to page tag to page nothing

after any fragment nothing nothing nothing

end of tag file restore tag to page tag to page

Save/restore means that the value of the variable from the page is saved on entry to tag
and the restored afterwards. Consequently, any changes made inside the tag are not visible
to the the page. The actions of the tag therefore apply only within the tag, which is suitable
for the NESTED scope.

Tag to page means that the value of the variable inside the tag is copied to the page's copy
of the variable. Consequently, for AT_END scope, the tag sees the initial value of the
variable from the page, and then exports the value back to the page at the end. For the
AT_BEGIN scope, the tag observes an uninitialized value for the variable, and exports it
back to the page at the end.

Is that any clearer?

Dynamic attributes

The tag directive can include a dynamic-attributes attribute, which gives the name of a map
which stores all of the tag attributes which are not explicitly declared. Here's an example of
how it can be used. First, the tag file (tabular.tag), which shows how to receive the
attributes via Java and using JSTL and expressions:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ tag import="java.util.*" %>
<%@ tag dynamic-attributes="attributes" %>
<%@ attribute name="title" %>

<%
out.println(jspContext.getAttribute("title"));
out.println("<table border='1'>");
Map m = (Map) jspContext.getAttribute("attributes");

© Aptech Ltd Version 1.0 175 of 194


Web Component Development Using Java References

for (Iterator i = m.keySet().iterator(); i.hasNext(); ) {


Object key = i.next();
Object val = m.get(key);
out.println("<tr>");
out.println("<td>" + key + "</td>");
out.println("<td>" + val + "</td>");
out.println("</tr>");
}
out.println("</table>");
%>

${title}
<table border='1'>
<c:forEach var="item" items="${attributes}">
<tr><td>${item.key}</td><td>${item.value}</td></tr>
</c:forEach>
</table>
And the jsp page:
<%@ taglib prefix="util" tagdir="/WEB-INF/tags" %>
<html>
<head>
</head>
<body>
<util:tabular title="Dynamic Attributes!" name="Fred" wife="Wilma"
friend="Barney" lover="Betty"/>
</body>
</html>
Which produces two copies of the following:
Dynamic Attributes!
wife Wilma
friend Barney
name Fred
lover Betty

© Aptech Ltd Version 1.0 176 of 194


Web Component Development Using Java References

JSP 2.0 Tags

Introduction

The second new mechanism in JSP 2.0 is a simplified approach to writing tags using Java
classes. It's based on the 'SimpleTag' interface, which is not even in the same class
hierarchy as the tag classes from JSP 1.0. It also uses the 'JspFragment' class to represent
sections of a JSP page. The implementation of tag files uses the JSP 2.0 tag approach; a JSP
2.0 tag is generated from the tag file.

The JSP 1.0 approach is similar to event-driven programming - the JSP code reacts to tag
start, end and body events. The JSP 2.0 approach is more top-down: the tag class has a
single method, doTag(), which is called when the tag is encountered, and the body is
presented to the tag class as a JspFragment.

To evaluate the body, the JspFragment class provides an invoke() method. For iterating
over the body, the tag class just calls invoke() in a loop. invoke() takes a writer as
parameter; you can supply a writer if you want to capture the output, or pass null to have it
write to the default stream.

Here's the SimpleTag interface:


public interface SimpleTag extends JspTag {
public void doTag()throws JspException, java.io.IOException;
public void setParent(JspTag parent);
public JspTag getParent();
public void setJspContext(JspContext pc);
public void setJspBody(JspFragment jspBody);
}

JspTag was introduced in 2.0 as a base interface for Tag and SimpleTag. It defines no
methods.

When implementing a simple tag, one typically derives from SimpleTagSupport. It provides
getJspBody() and findAncestorWithClass() methods.

When the doTag() method is called, setters for all attributes, and the setJspBody() method
(if necessary) will have been called. The entire processing of the tag therefore takes place in
doTag().

The JspContext object replaces the page context object used in JSP 1.0 tags. The idea is
that this object is not dependent on http servlet classes, making the approach more generic.

© Aptech Ltd Version 1.0 177 of 194


Web Component Development Using Java References

The body is available to the tag as a JspFragment, but it is also possible to define attributes
as fragments. In this case the setter method must accept a JspFrament object, and the
attribute must be declared as a fragment in the descriptor file. This approach is useful when
the tag needs to display different template text depending on runtime conditions.

Example

Here's a rather complicated example. The idea is to build a table of primes, where the
background color of each row indicates whether the prime is even, or of the forms 4k+1 or
4k+3. This is interesting (to some), since Fermat proved that all primes of the form 4k+1
can be written as the sum of two squares, while all primes of the form 4k+3 cannot be so
written. That's interesting, isn't it? The JSP page, test-fragment.jsp, appears below. Note
how all of the template text that builds the table is contained in the JSP page. The
conditional parts, which define the background color of the row, depending on the prime in
question, appear as attributes of the custom tag.
<%@ taglib prefix='asitl' uri='http://www.alethis.net/tags/asitl' %>
<html>
<head>
<title>JSP Test Tag</title>
</head>
<body>
<asitl:primes>
<jsp:attribute name="count">
10
</jsp:attribute>
<jsp:attribute name="evens">
<tr bgcolor='lightgreen'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:attribute name="odds1">
<tr bgcolor='cyan'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:attribute name="odds3">
<tr bgcolor='pink'><td>${index}</td><td>${value}</td></tr>
</jsp:attribute>
<jsp:body>
<table border='1' cellpadding='3'>

© Aptech Ltd Version 1.0 178 of 194


Web Component Development Using Java References

<tr><th>Position</th><th>Prime</th><tr>
${content}
</table>
</jsp:body>
</asitl:primes>
</body>
</html>
The output:
Position Prime
1 2
2 3
3 5
4 7
5 11
6 13
7 17
8 19
9 23
10 29

The descriptor file:


<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns='http://java.sun.com/xml/ns/j2ee'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd'
version='2.0'>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<uri>http://www.alethis.net/tags/asitl</uri>
...
<tag>
<name>primes</name>
<tag-class>net.alethis.tags.PrimesTag</tag-class>

© Aptech Ltd Version 1.0 179 of 194


Web Component Development Using Java References

<body-content>scriptless</body-content>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>evens</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<attribute>
<name>odds1</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<attribute>
<name>odds3</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<fragment>true</fragment>
</attribute>
<variable>
<name-given>index</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
<variable>
<name-given>value</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>

© Aptech Ltd Version 1.0 180 of 194


Web Component Development Using Java References

<scope>NESTED</scope>
</variable>
<variable>
<name-given>content</name-given>
<variable-class>java.lang.String</variable-class>
<declare>true</declare>
<scope>NESTED</scope>
</variable>
</tag>
</taglib>

The implementation class, PrimesTag.java. Note how the output from the attribute
fragments is captured, while the output from the body fragment is just sent to the standard
output writer.
package net.alethis.tags;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class PrimesTag extends SimpleTagSupport {


private String countString;
private JspFragment evensFragment;
private JspFragment odds1Fragment;
private JspFragment odds3Fragment;
public void setCount(String s) {
countString = s;
}
public void setEvens(JspFragment f) {
evensFragment = f;
}
public void setOdds1(JspFragment f) {
odds1Fragment = f;
}
public void setOdds3(JspFragment f) {

© Aptech Ltd Version 1.0 181 of 194


Web Component Development Using Java References

odds3Fragment = f;
}
public void doTag() throws JspException {
try {
int count = Integer.parseInt(countString);
StringWriter sw = new StringWriter();
int lastPrime = 0;
int total = 0;
for (int i = 1; total < count; i++) {
int p = nextPrime(lastPrime);
total++;
getJspContext().setAttribute("index", String.valueOf(total));
getJspContext().setAttribute("value", String.valueOf(p));
if (p % 2 == 0) {
evensFragment.invoke(sw);
}
else if (p % 4 == 1) {
odds1Fragment.invoke(sw);
}
else if (p % 4 == 3) {
odds3Fragment.invoke(sw);
}
lastPrime = p;
}
getJspContext().setAttribute("content", sw.toString());
getJspBody().invoke(null);
}
catch (Exception e) {
throw new JspTagException("error in RepeatTag: " + e.getMessage());
}
}
private int nextPrime(int start) {
for (int k = start + 1; ; k++) {
if (k < 2) {

© Aptech Ltd Version 1.0 182 of 194


Web Component Development Using Java References

continue;
}
boolean isPrime = true;
int sqrt = (int) Math.sqrt(k);
for (int m = 2; m <= sqrt; m++) {
if (k % m == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
return k;
}
}
}
}

The war file structure:

test-primes.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PrimesTag.class

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 183 of 194


Web Component Development Using Java References

Session 14: Internationalization

Ser vlet Inter nationalization

Source http://www.devmanuals.com/tutorials/java/servlet/servlet-
internationalization.html
Date of 02/04/2015
Retrieval

Hi you can localized your web application so that it can diplays in client's native language,
Or you can use any pericular language. This can be done easily from properties files. This
file is also called the message resources. It the contains the message in the form of key and
values. For localizations you have to only do that, maintain the individual file for the each
language. The following is the to properties files for English and Spanish language
respectively.

message_en.properties

browser.detected.lang.code = Browser Detected Language Code


page.title = Servlet Internationalization example
page.change.lang.button = Change
page.change.lang.caption = Change Language
page.change.lang.choose = Choose Language
page.change.lang.choose.eng = English
page.change.lang.choose.spa = Spanish

page.heading = Please Fill up the form


page.form.name = Name
page.form.course = Course
page.form.address = Address

message_es.properties

browser.detected.lang.code = Navegador idioma detectado Código


page.title = Ejemplo de la internacionalización Servlet
page.change.lang.button = cambiar
page.change.lang.caption = Cambiar idioma
page.change.lang.choose = Elegir idioma
page.change.lang.choose.eng = Inglés
page.change.lang.choose.spa = español

page.heading = Por favor, Rellene el formulario


page.form.name = nombre
page.form.course = curso
page.form.address = dirección

© Aptech Ltd Version 1.0 184 of 194


Web Component Development Using Java References

Please note that some special characters are not displayed properly. To display them
properly your properties file must be in UTF-8 format, and at the top of your page you must
add the UTF-8 header as,
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

You can add this properties file in your application in your servlet as,
ResourceBundle bundle = ResourceBundle.getBundle("locale/message_en",
locale);

And get the text from the properties file as


bundle.getString("page.heading");

A sample servlet class is given below


SampleInterfaceImp.java
package devmanuals.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InternationalizationServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
Locale locale = request.getLocale();
String lang = "";

if (request.getParameter("cngLng") != null) {
String optional = request.getParameter("cngLng");
if (!optional.equals("select")) {
lang = (String) request.getParameter("cngLng");
}
} else {
lang = locale.getLanguage();
}

ResourceBundle bundle = ResourceBundle.getBundle("locale/message_"+ lang,


locale);
out.println("<h3 align='center'>"
+ bundle.getString("browser.detected.lang.code") + "- "
+ locale.getLanguage() + "</h3>");
out.println("<H2 align='center'>" + bundle.getString("page.heading")
+ "</H2>");
out.print("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'
/>");
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0

© Aptech Ltd Version 1.0 185 of 194


Web Component Development Using Java References

Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>" + bundle.getString("page.title") + "</TITLE>");
out.println("</HEAD>");

out.println("<BODY>");
out.println("<form name='cngLocale' action='internationalization.html'
method='post'>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td>" + bundle.getString("page.change.lang.caption")
+ "</td>");
out.println("<td>");
out.println("<select name='cngLng' id='cngLng'>");
out.println("<option value='select' selected='selected'>"
+ bundle.getString("page.change.lang.choose") + "</option>");
out.println("<option value='es'>"
+ bundle.getString("page.change.lang.choose.spa") + "</option>");
out.println("<option value='en'>"
+ bundle.getString("page.change.lang.choose.eng") + "</option>");
out.println("</select>");
out.println("</td>");
out.println("<td><input type='submit' value='"
+ bundle.getString("page.change.lang.button") + "'/></td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");

out.println("<form name='myForm' action='#' method='post'>");


out.println("<table align='center'>");
out.println("<tr>");
out.println("<td>" + bundle.getString("page.form.name") + "</td>");
out.println("<td><input type='text' name='name' id='name'/></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>" + bundle.getString("page.form.course") + "</td>");
out.println("<td><input type='text' name='course' id='course'/></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>" + bundle.getString("page.form.address") + "</td>");
out.println("<td><input type='text' name='name' id='address'/></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td colspan='2' align='center'><input type='submit'
value='Submit'/></td>");
out.println("</tr>");
out.println("</table>");
out.println(" </form>");
out.println("</BODY>");
out.println("</HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

© Aptech Ltd Version 1.0 186 of 194


Web Component Development Using Java References

When you run this application it will display message as shown below:

In English

In Spanish..

© Aptech Ltd Version 1.0 187 of 194


Web Component Development Using Java References

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 188 of 194


Web Component Development Using Java References

Session 15: Securing Web Applications

JSP Security in Java

Source http://mrbool.com/jsp-security-in-java/28556
Date of 02/04/2015
Retrieval

JavaServer Pages and servlets make several mechanisms available to Web developers to
secure applications. Resources are secured declaratively by verifying them in the application
deployment descriptor and assigning a role to them.

Several levels of evidence are available, ranging from basic authentication using identifiers
and passwords to sophisticated authentication using certificates.

Role Based Authentication:


The certification mechanism in the servlet specification uses a mechanism called role-based
security. This idea is that rather than limiting resources at the user level, we create roles
and restrict the resources by role.

We can define different roles in file tomcat-users.xml, which is placed at Tomcat's home
directory in conf. An example demonstrates the above:

Listing 1: Defining different roles

<?xml version='1.0' encoding='utf-8'?>


<tomcat-users>
<role rolename="tom cat"/>
<role rolename="rol e1"/>
<role rolename="man ager"/>
<role rolename="adm in"/>
<user username="tom cat" password="tomca t" roles="tomcat"/>
<user username="rol e1" password="tomcat " roles="role1"/>
<user username="bot h" password="tomcat" roles="tomcat,manag er"/>
<user username="adm in" password="secret " roles="admin,role1 "/>
</tomcat-users>

This file defines a mapping between user name, password, and role. Concern that a given
user may have more than one role, for example, user name="both" is in the "tomcat" role
and the "role1" role.

Once we identified and defined different roles, a role-based security limitations can be
placed on different Web Application resources by using the <security-constraint> element in
web.xml file present in WEB-INF directory.

© Aptech Ltd Version 1.0 189 of 194


Web Component Development Using Java References

Listing 2: web.xml sample entry

<web-app>
...
<security-constrai nt>
<web-resource-coll ection>
<web-resource-name >
SecuredBookSite
</web-resource-nam e>
<url-pattern>/secur e</url-pattern>
<http-method>POST</ http-method>
<http-method>GET</h ttp-method>
</web-resource-coll ection>
<auth-constraint>
<description>
Only admin can use this app
</description>
<role-name>admin</ role-name>
</auth-constraint>
</security-constrai nt>
<security-role>
<role-name>role1r</ role-name>
</security-role>
<login-config>
<auth-method>BASIC </auth-method>
</login-config>
...
</web-app>

Above entries would mean:

Any HTTP GET or POST request to a URL checked by /secured/* would be subject to the
security restriction.

A person with admin role is given authority to the secured resources.The login-config
element is used to explain the BASIC form of certification. Now if we try browsing to any
URL including the /security directory, it would show a dialogue box asking for user name
and password. If we provide a user "admin" and password "securer" then only we would
have access on URL matched by /secured/* because above we have defined user admin
with manager role who is allowed to access this resource.

Form Based Authentication:


When we use the FORM authentication method, we must supply a login form to prompt the
user for a username and password. Following is a simple code of loginpage.jsp to create a
form for the same purpose:

Listing 3: Simple code of loginpage.jsp

<html>
<body bgcolor="#fff fff">
<form method="PO ST" action="j_securi ty_check">
<table border ="0">
<tr>
<td>Login</td >
<td><input ty pe="text" name="j_us ername"></td>

© Aptech Ltd Version 1.0 190 of 194


Web Component Development Using Java References

</tr>
<tr>
<td>Password< /td>
<td><input ty pe="password" name=" j_password"></td>
</tr>
</table>
<input type=" submit" value="Login !">
</center>
</form>
</body>
</html>
Here we have to make sure that the login form must contain form elements named
j_username and j_password. The action in the <form> tag must be j_security_check. GET
must be used as the one of form method.

Same time we would have to modify <login-config> tag to specify auth-method as FORM:

Listing 4: auth-method code

<web-app>
...
<security-const raint>
<web-resour ce-collection>
<web-re source-name>
Secu redBookSite
</web-r esource-name>
<url-pa ttern>/secured/*</ur l-pattern>
<http-m ethod>GET</http-meth od>
<http-m ethod>POST</http-met hod>
</web-resou rce-collection>
<auth-const raint>
<descri ption>
Let use this app only by ma nagers
</descr iption>
<role-n ame>manager</role-na me>
</auth-cons traint>
</security-cons traint>
<security-role>
<role-name >manager</role-name>
</security-role >
<login-config>
<auth-method> FORM</auth-method>
<form-login-c onfig>
<form-login -page>/loginpage.jsp </form-login-page>
<form-error -page>/errorpage.jsp </form-error-page>
</form-login- config>
</login-config>
...
</web-app>

Now when we try to access any resource with URL /secured/*, it would display above form
asking for user id and password. When the container sees the "j_security_check" action, it
follows some internal mechanism to verify the caller.

© Aptech Ltd Version 1.0 191 of 194


Web Component Development Using Java References

If the login succeeds and the caller is authorized to access the secured resource, then the
server uses a session-id to identify a login session for the caller from that point. The server
maintains the login session with a cookie containing the session-id. The server returns the
cookie back to the client, and as long as the caller exist this cookie with frequent requests,
then the server will know who the caller is.

If the login fails, then the server sends back the page identified by the form-error-page
setting

Here j_security_check is the action that applications using form based login have to specify
for the login form. In the same form we have a text input control called j_username and a
password input control called j_password. When we watch this it means that the information
contained in the form will be stored to the server, which will verify name and password.
How this can be made server specific.

Programmatic Security in a Servlet/JSP:


The HttpServletRequest object provides the below methods, which can be used to get
security information at runtime:

Listing 5: Demo of getAuthType Method

import java.util.*;
import java.io.*;
import javax.servle t.*;
import javax.servle t.http.*;
import java.securit y.*;
public class MyServ let extends HttpServ let {

public void ini t(ServletConfig cfg) throws ServletExcep tion


{
super.init( cfg);
}

© Aptech Ltd Version 1.0 192 of 194


Web Component Development Using Java References

public void doG et(HttpServletReques t request, HttpServl etResponse


response)
throws IOEx ception, ServletExce ption
{
response.se tContentType("text/h tml");
PrintWriter out = response.getW riter();

out.println ("<HTML>");
out.println ("<HEAD>");
out.println ("<TITLE>");
out.println ("User Authenticatio n");
out.println ("</TITLE>");
out.println ("</HEAD>");
out.println ("<BODY>");
out.println ("<H1>User Authentic ation</H1>");

String type = request.getAuthTy pe();


out.println ("Welcome User<BR>") ;
out.println ("Authentication mec hanism: " + type + " <BR>");
Principal p = request.getUserPr incipal();
out.println ("Wer username is: " + p.getName() + "<B R>");

out.println ("</BODY>");
out.println ("</HTML>");
}
}
Output:

Welcome User
Authentication mechanism:Manager
Wer username is:Joe

For example, a JavaServer Page that links to pages for managerswe might have the
following snippet:

Listing 6: Snippet

<% if (request.isUs erInRole("manager")) { %>


<a href="managers/m grreport.jsp">Manage r Report</a>
<a href="managers/p ersonnel.jsp">Person nel Records</a>
<% } %>

By checking the user's role in a JSP or servlet, we can personalize the Web page to show
the user only the items they can use. If we need the user's name as it was entered in the
evidence form, we can call getRemoteUser method in the request object.

© Aptech Ltd Version 1.0 193 of 194


Web Component Development Using Java References

Conclusion
Java security technology includes a large set of APIs, tools, and fulfillment of commonly
used security algorithms, protocols and mechanisms. The Java security APIs spans a wide
range of areas, including public key infrastructure, cryptography and authentication, secures
communication and use control. Java security technology bestows the programmer with a
comprehensive security framework for writing applications, and also bestows the user or
administrator with a set of tools to securely manage applications.

~~~ End of Article ~~~

© Aptech Ltd Version 1.0 194 of 194

You might also like