References 60
References 60
Table of Contents
S#. Session Page No.
1. Session 1: Introduction to Web Applications
● History of Web Applications 4
Page Generation 21
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.
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
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.
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.
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.
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.
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/.
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
Figure 1-3, server extensions exist within the main process of a web server.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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!
Login.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
PrintWriter out=response.getWriter();
java.util.Date tody=new java.util.Date();
out.println("output html tags");
}
}
web.xml
<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>
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.
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.
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.
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.
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.
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.
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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.
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.
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.
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.
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.
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>
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.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
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.
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:
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.
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.
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.
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.*;
// 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.
Date of 02/04/2015
Retrieval:
Methods of RequestDispatcher
Methods Description
of RequestDispatcher.
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);
OR
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);
Files to be created :
index.html
</form>
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
try {
if(password.equals("studytonight"))
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);
else
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.*;
response.setContentType("text/html;charset=UTF-8");
try {
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>
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.
Password will be successfully validated and you will be directed to the Welcome Servlet.
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?
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),
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).
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.
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:
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.
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.
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);
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.*;
(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>");
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:
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.
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>
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.
<session-config>
<cookie-config>
<secure>true</secure>
</cookie-config>
</session-config>
<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
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.
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.
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:
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.
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
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.
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.
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.
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.
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.
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.
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/"
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/upload/");
/*
* 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;
//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.
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");
}
<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>
Source http://www.informit.com/articles/article.aspx?p=170963&seqNum=7
Date of 02/04/2015
Retrieval:
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.
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.
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.
package com.jspbook;
import javax.servlet.*;
import javax.servlet.http.*;
public class ConcurrentUserTracker implements HttpSessionListener {
static int users = 0;
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.
<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.
package com.jspbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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>");
}
}
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.
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.
Class representing the execution context for an asynchronous operation that was initiated
on a ServletRequest.
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.
1import java.io.IOException;
2 import java.io.PrintWriter;
3 import javax.servlet.AsyncContext;
4 /**
6 */
9 /**
12 */
14
16 this.aContext = aContext;
17 }
18
19 @Override
22
23 try {
//Retrieve the type parameter from the request. This is passed in the
24
URL.
26
29
31
32 out = aContext.getResponse().getWriter();
33
35 Thread.sleep(5000);
36
37 /**
39 */
40 switch (typeParam) {
41 case "1":
43 break;
44 case "2":
46 break;
47 default:
49 break;
50 }
51
53
54 /**
57 */
58 aContext.complete();
59
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.
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.
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
4 var counter1;
5 var counter2;
8 function setupEventHandlers() {
9 counter1 = 1;
10 counter2 = 1;
13 ajaxBtn1.onclick = handleAjaxBtn1;
14 ajaxBtn2.onclick = handleAjaxBtn2;
15
16 }
17
19
20 function handleAjaxBtn1(){
xmlhrObj.open("GET", "http://localhost:8080/DemoApplication/asyncHello?type=1&counter=
22
+counter1, true);
23 counter1++;
24 xmlhrObj.onreadystatechange = function(){
27 div1.innerHTML = xmlhrObj.responseText;
28 }
29 };
30 xmlhrObj.send();
31 }
32
33 function handleAjaxBtn2(){
xmlhrObj.open("GET", "http://localhost:8080/DemoApplication/asyncHello?type=2&counter=
35
+counter2, true);
36 counter2++;
37 xmlhrObj.onreadystatechange = function(){
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~~~
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"
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.
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.
pageEncoding="UTF-8"%>
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 © 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();
%>
Implicit Objects
Source https://docs.oracle.com/cd/E19316-01/819-3669/bnaij/index.html
Date of 02/04/2015
Retrieval:
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:
Finally, there are objects that allow access to the various scoped variables using scope objects.
JSP 2.1 provides two EL resolvers to handle expressions that reference these
objects: ImplicitObjectELResolver and ScopedAttributeELResolver.
object is found, the MapELResolver instance resolves the profile attribute because
the profile object represents a map.
${sessionScope.profile}
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.
JavaBeans Concepts
Source http://da2i.univ-lille1.fr/doc/tutorial-java/javabeans/whatis/index.html
Date of 24/07/2014
Retrieval:
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.
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.
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:
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.
To collect this data, we define a Java class with fields "username", "email" and "age" and
we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter"
method is just a method that starts with "set" followed by the name of the field. The first
character of the field name is upper-cased. So if the field is "email", its "setter" method
will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note
that the setters (and getters) must be public.
package user;
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.
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!
Notice that the same useBean tag is repeated. The bean is available as the variable named
"user" of class "user.UserData". The data entered by the user is all collected in the bean.
We do not actually need the "SaveName.jsp", the target of GetName.html could have been
NextPage.jsp, and the data would still be available the same way as long as we added a
jsp:setProperty tag. But in the next tutorial, we will actually use SaveName.jsp as an error
handler that automatically forwards the request to NextPage.jsp, or asks the user to
correct the erroneous data.
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
Creating Controller
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:
3. Type an integer number, select a method and click on Calculate, you will get the
corresponding result.
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.
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:
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.
To summarize, the new, unified expression language allows page authors to use simple
expressions to perform the following tasks:
The unified EL also allows custom tag developers to specify which of the following kinds of
expressions that a custom tag attribute will accept:
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.
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.
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.
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 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:
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.
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
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:
${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.
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}
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:
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.
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:
<some:tag value="some${expr}${expr}text${expr}"/>
<another:tag value="some#{expr}#{expr}text#{expr}"/>
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.
<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.
<h:form>
<h:inputText
id="name"
value="#{customer.name}"
validator="#{customer.validateName}"/>
<h:commandButton
id="submit"
action="#{customer.submit}" />
</h:form>
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:
<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.
<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.
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.
To escape the #{ or ${ characters in the page, you use the \ character as follows:
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:
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.
${’${’}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.
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:
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
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.
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.
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.
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.
JSP 2.1 provides two EL resolvers to handle expressions that reference these objects:
ImplicitObjectELResolver and ScopedAttributeELResolver.
${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:
== != 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.
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:
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.
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.
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 :
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.
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
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:
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:
USD,EUR,AUD,INR
</c:set>
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> 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:
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 :
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.
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:
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.
JSP Tags
Source http://www.alethis.net/reference/java/jsptags.html#Custom_Tags
Date of 02/04/2015
Retrieval
Custom TagsCustgs
The variable element defines an exported scripting variable and has the following attributes:
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.
declare Whether the variable refers to a new object. The default is true.
required Whether the attribute is required or not: 'true', 'false', 'yes' or 'no'
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" ?>
import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
</taglib>
The implementation class, PowerTag.java:
package net.alethis.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
lib
jstl.jar
standard.jar
</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 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
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.*;
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
<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.*;
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;
}
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
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
<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.*;
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 {
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
<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.*;
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
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.*;
}
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
<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 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.*;
}
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
request
response
session
application
out
config
jspContext
Directives
Directives available in tag files:
variable define a scripting variable that becomes visible in the JSP page
dynamic- specifies the name of a map that will receive all undeclared
attributes attributes
display-name for tools - optional - default is the tag file name, minus extension
rtexprvalue true or false - indicates whether runtime expressions are accepted; true
is the default
fragment true or false - should the value be evaluated by the container (false), or
passed directly to the tag handler (true)
<html>
<head>
</head>
<body>
Let's get some sleep! <util:repeater count='${3 * 10}' value='zzz'/>
</body>
</html>
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.
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.
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" %>
<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>
</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:
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(); ) {
${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
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.
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'>
<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
<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>
<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.*;
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
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:
release - ???
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>
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.
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.
declare Whether the variable refers to a new object. The default is true.
required Whether the attribute is required or not: 'true', 'false', 'yes' or 'no'
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" ?>
<!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.*;
}
catch (Exception e) {
throw new JspTagException("error in CurrentDateTag: " +
e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
The attributes are received in the tag class via setter methods.
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
test-attributes.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
CurrentDateTag.class
lib
jstl.jar
standard.jar
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.
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
This example conditionally includes the body depending on the value of an attribute.
<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.*;
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
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
test-iterate.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
RepeatTag.class
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.
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>
import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
bc.clearBody();
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;
}
return SKIP_BODY;
}
catch (Exception e) {
throw new JspTagException("error in EvaluateTag: " +
e.getMessage());
}
}
public int doEndTag() {
return EVAL_PAGE;
}
}
test-read-body.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
EvaluateTag.class
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.
</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>
<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>
package net.alethis.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
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++;
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());
}
}
}
test-variable.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PowerTableTag.class
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>
</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.*;
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
the tld descriptor file must indicate that the tag accepts dynamic attributes (and must use
the JSP 2.0 DTD!).
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'
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.*;
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.
<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.*;
}
}
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.*;
test-wall.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
BottleTag.class
WallTag.class
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.
request
response
session
application
out
config
jspContext
</html>
Directives
variable define a scripting variable that becomes visible in the JSP page
import imports classes or packages; this attribute can appear multiple times
dynamic-attributes specifies the name of a map that will receive all undeclared
attributes
display-name for tools - optional - default is the tag file name, minus extension
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 attribute directive declares an attribute that the tag accepts. The attributes of the
attribute directive are:
name the name of the attribute
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.
alias A locally scoped variable which will store the variable's value. Used only with
name-from-attribute.
scope The variable's scope; possible values are AT_BEGIN, AT_END and NESTED.
NESTED is the default.
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");
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.
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");
${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
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.
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">
<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
<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>
<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.*;
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) {
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;
}
}
}
}
test-primes.jsp
WEB-INF
asitl.tld
classes
net
alethis
tags
PrimesTag.class
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
message_es.properties
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);
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;
if (request.getParameter("cngLng") != null) {
String optional = request.getParameter("cngLng");
if (!optional.equals("select")) {
lang = (String) request.getParameter("cngLng");
}
} else {
lang = locale.getLanguage();
}
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>");
When you run this application it will display message as shown below:
In English
In Spanish..
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.
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:
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.
<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>
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.
<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>
</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:
<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.
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.
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 {
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>");
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
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.
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.