JavaServer Faces Introduction by Example Juneau Josh
JavaServer Faces Introduction by Example Juneau Josh
JavaServer Faces Introduction by Example Juneau Josh
JavaServer Faces Introduction by Example Juneau Josh
1. Explore the full ebook collection and download it now at textbookfull.com
JavaServer Faces Introduction by Example Juneau
Josh
https://textbookfull.com/product/javaserver-faces-
introduction-by-example-juneau-josh/
OR CLICK HERE
DOWLOAD EBOOK
Browse and Get More Ebook Downloads Instantly at https://textbookfull.com
Click here to visit textbookfull.com and download textbook now
2. Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...
Read anywhere, anytime, on any device!
Mastering JavaServer Faces 2 2 Leonard Anghel
https://textbookfull.com/product/mastering-javaserver-
faces-2-2-leonard-anghel/
textbookfull.com
Java 8 Recipes 2nd Edition Josh Juneau
https://textbookfull.com/product/java-8-recipes-2nd-edition-josh-
juneau/
textbookfull.com
Java 9 Recipes: A Problem-Solution Approach 3rd Edition
Josh Juneau
https://textbookfull.com/product/java-9-recipes-a-problem-solution-
approach-3rd-edition-josh-juneau/
textbookfull.com
Java EE 7 Recipes A Problem Solution Approach 1st Edition
Juneau Josh
https://textbookfull.com/product/java-ee-7-recipes-a-problem-solution-
approach-1st-edition-juneau-josh/
textbookfull.com
3. Introducing Java EE 7 A Look at What s New Juneau Josh
https://textbookfull.com/product/introducing-java-ee-7-a-look-at-what-
s-new-juneau-josh/
textbookfull.com
The Definitive Guide to JSF in Java EE 8: Building Web
Applications with JavaServer Faces Bauke Scholtz
https://textbookfull.com/product/the-definitive-guide-to-jsf-in-java-
ee-8-building-web-applications-with-javaserver-faces-bauke-scholtz/
textbookfull.com
JavaFX 2 0 Introduction by Example Expert s Voice in Java
Dea Carl
https://textbookfull.com/product/javafx-2-0-introduction-by-example-
expert-s-voice-in-java-dea-carl/
textbookfull.com
JavaFX 9 by Example Dea
https://textbookfull.com/product/javafx-9-by-example-dea/
textbookfull.com
Blazor WebAssembly By Example Second Edition --
https://textbookfull.com/product/blazor-webassembly-by-example-second-
edition/
textbookfull.com
6. For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
7. v
Contents at a Glance
About the Author��������������������������������������������������������������������������������������������������������������xvii
Acknowledgments�������������������������������������������������������������������������������������������������������������xix
Chapter 1: Introduction to Servlets
■
■ �����������������������������������������������������������������������������������1
Chapter 2: JavaServer Pages
■
■ ������������������������������������������������������������������������������������������55
Chapter 3: The Basics of JavaServer Faces
■
■ ��������������������������������������������������������������������99
Chapter 4: Facelets
■
■
��������������������������������������������������������������������������������������������������������163
Chapter 5: JavaServer Faces Standard Components
■
■ ����������������������������������������������������205
Chapter 6: Advanced JavaServer Faces and Ajax
■
■ ���������������������������������������������������������261
Index���������������������������������������������������������������������������������������������������������������������������������325
8. 1
Chapter 1
Introduction to Servlets
Java servlets were the first technology for producing dynamic Java web applications. Sun Microsystems released the
first Java Servlet specification in 1997. Since then it has undergone tremendous change, making it more powerful
and easing development more with each release. The 3.0 version was released as part of Java EE 6 in December
2009. Although not always used directly by Java web developers, servlets are at the base of all Java EE applications.
Many developers use servlet frameworks such as Java Server Pages (JSP) and Java Server Faces (JSF), both of those
technologies compile pages into Java servlets behind the scenes via the servlet container. That said, a fundamental
knowledge of Java servlet technology is very useful for any Java web developer.
Servlets are Java classes that conform to the Java Servlet API, which allows a Java class to respond to requests.
Although servlets can respond to any type of request, they are most commonly written to respond to HTTP requests.
A servlet must be deployed to a Java servlet container in order to become usable. The Servlet API provides a number
of objects that are used to enable the functionality of a servlet within a web container. Such objects include the
request and response objects, pageContext, and a great deal of others, and when these objects are used properly, they
enable a Java servlet to perform just about any task a web-based application needs to perform.
As mentioned, servlets can produce not only static content but also dynamic content. Since a servlet is written in
Java, any valid Java code can be used within the body of the servlet class. This empowers Java servlets and allows them
to interact with other Java classes, the web container, the underlying file server, and much more.
This chapter will get you started developing and deploying servlets, and provide you with foundational
knowledge to move forward with other servlet-based web frameworks In this chapter, you will learn how to install
Oracle’s GlassFish application server, a robust servlet container, which will enable you to deploy sophisticated Java
enterprise applications. You will be taught the basics of developing servlets, how to use them with client web sessions,
and how to link a servlet to another application. All the while, you will learn to use standards from the latest release of
the Java Servlet API (3.2), which modernizes servlet development and makes it much easier and more productive than
in years past.
Note
■
■ You can run the examples within this chapter by deploying the JSFByExample.war file (contained in the
sources)
to a local Java EE application server container such as GlassFish v4.x. You can also set up the NetBeans 8.x project entitled
JSFByExample that is contained in the sources, build it, and deploy to GlassFish v4.x. Otherwise, you can run the examples
in Chapter 1 stand-alone using the instructions provided in the section “Packaging, Compiling, and Deploying a Servlet”.
If you deploy the JSFByExample.war file to a Java EE application server container, you can visit thefollowing URL to load
the examples for this chapter: http://localhost:8080/JSFByExample/faces/chapter01/index.xhtml.
9. Chapter 1 ■ Introduction to Servlets
2
Setting Up a Java Enterprise Environment
You’ll need an environment in which to experiment with servlets, and then later with JavaServer Faces. Oracle’s
GlassFish application server is a good choice, as it is the Java EE 7 Reference Impementation. It’s easy to set up, and
the following example will get you started and ready to run all the subsequent examples in the book.
Example
To get started, ownload and install Oracle’s GlassFish application server from the GlassFish web site. The version used
for this book is the open source edition, release 4.1, and it can be downloaded from http://glassfish.java.net/ in
the “Download” section. Select the .zip or .tar.gz download format, and decompress the downloaded files within a
directory on your workstation. I will refer to that directory as /JAVA_DEV/GlassFish. The GlassFish distribution comes
prepackaged with a domain so that developers can get up and running quickly. Once the .zip file has been unpacked,
you can start the domain by opening a command prompt or terminal and starting GlassFish using the following
statement:
/PATH_TO_GLASSFISH /GlassFish/bin/asadmin start-domain domain1
The domain will start, and it will be ready for use. You will see output from the server that looks similar to the
following:
Waiting for domain1 to start ............
Successfully started the domain : domain1
domain Location: /PATH_TO_GLASSFISH/glassfish/domains/domain1
Log File: /PATH_TO_GLASSFISH/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.
Explanation
The development of Java EE applications begins with a Java EE–compliant application server. A Java EE–compliant
server contains all the essential components to provide a robust environment for deploying and hosting enterprise
Java applications. The GlassFish application server is the industry standard for Java EE 7. As of GlassFish 4.0, there is
only an open sourced distribution of the server available, meaning that it is not possible to purchase Oracle support
for GlassFish. However, in a production environment, you may want to consider purchasing GlassFish 4.x support
from a third-party organization so that technical support will be available if needed. An alternative is to utilize a
commercially supported server that is Java EE 7 compliant, such as Oracle WebLogic 12.1.x.
Installing GlassFish is easy. It consists of downloading an archive and uncompressing it on your development
machine. Once you’ve completed this, the application server will make use of your locally installed Java development
kit (JDK) when it is started. JDK 8 is supported for use with GlassFish as of release 4.1. For GlassFish 4.0, please
use JDK 7. Once the server starts, you can open a browser and go to http://localhost:4848 to gain access to the
GlassFish administrative console. Most Java EE developers who deploy on GlassFish use the administrative console
often. The administrative console provides developers with the tools needed to deploy web applications, register
databases with Java Naming and Directory Interface (JNDI), set up security realms for a domain, and do much more.
You should take some time to become familiar with the administrative console because the more you know about it,
the easier it will be to maintain your Java EE environment.
Installing the GlassFish application server is the first step toward developing Java applications for the enterprise.
While other applications servers such as JBoss WildFly, Apache TomEE, and WebLogic are very well adopted,
GlassFish offers developers a solid environment that is suitable for production use and easy to learn. It also has the
bonus of being an open source application server and the reference implementation for Java EE 7.
10. Chapter 1 ■ Introduction to Servlets
3
Developing Your First Servlet
Web applications are based upon a series of web views or pages. There is often a requirement to develop a view that
has the ability to include content that may change at any given time. For instance, you may be developing a view
that contains stock data, and you may wish to have that data updated often. Servlets provide the ability to produce
dynamic content, allowing server-side computations and processes to update the data in the servlet at will.
Example
Develop a Java servlet class, and compile it to run within a Java servlet container. In this example, a simple servlet
is created that will display some dynamic content to the web page. The The following code is the servlet code that
contains the functionality for the servlet:package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Simple Dynamic Servlet
* @author juneau
*/
public class SimpleServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* codeGET/code and
* codePOST/code methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html;charset=UTF-8);
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
out.println(html);
out.println(head);
out.println(titleServlet SimpleServlet/title);
out.println(/head);
out.println(body);
out.println(h2Servlet SimpleServlet at + request.getContextPath() + /h2);
out.println(br/Welcome to JavaServer Faces: Introduction By Example!);
11. Chapter 1 ■ Introduction to Servlets
4
out.println(/body);
out.println(/html);
} finally {
out.close();
}
}
// editor-fold defaultstate=collapsed desc=HttpServlet methods. Click on the + sign on the
left to edit the code.
/**
* Handles the HTTP
* codeGET/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* codePOST/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return Short description;
}// /editor-fold
}
12. Chapter 1 ■ Introduction to Servlets
5
The following code is the web deployment descriptor. This file is required for application deployment to a servlet
container. It contains the servlet configuration and mapping that maps the servlet to a URL. Later in this chapter,
will learn how to omit the servlet configuration and mapping from the web.xml file to make servlet development,
deployment, and maintenance easier.
?xml version=1.0?
web-app xmlns=http://java.sun.com/xml/ns/javaee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd
version=3.0
servlet
servlet-nameSimpleServlet/servlet-name
servlet-classorg.javaeeexamples.chapter1.example01_02.SimpleServlet/servlet-class
/servlet
servlet-mapping
servlet-nameSimpleServlet/servlet-name
url-pattern/SimpleServlet/url-pattern
/servlet-mapping
welcome-file-list
welcome-file /SimpleServlet /welcome-file
/welcome-file-list
/web-app
Note
■
■ Many web applications use a page named index.html or index.xhtml as their welcome file. There is nothing
wrong with doing that, and as a matter of fact, it is the correct thing to do. The use of /SimpleServlet as the welcome
file in this example is to make it easier to follow for demonstration purposes.
To compile the Java servlet, use the javac command-line utility. The following line was excerpted from the
command line, and it compiles the SimpleServlet.java file into a class file. First, traverse into the directory
containing the SimpleServlet.java file; then, execute the following:
javac -cp /JAVA_DEV/GlassFish/glassfish/modules/javax.servlet-api.jar SimpleServlet.java
Once the servlet code has been compiled into a Java class file, it is ready to package for deployment.
Note
■
■ You may want to consider installing a Java integrated development environment (IDE) to increase your develop-
ment productivity. There are several very good IDEs available to developers, so be sure to choose one that contains the
features you find most important and useful for development. As the author of this book on Java EE 7, I recommend
installing NetBeans 8.x or newer for development. NetBeans is an open source IDE that is maintained by Oracle, and it
includes support for all the cutting-edge features that the Java industry has to offer, including EJB development with Java
EE 7, JavaFX 8 support, and more.
13. Chapter 1 ■ Introduction to Servlets
6
Explanation
Java servlets provide developers with the flexibility to design applications using a request-response programming
model. Servlets play a key role in the development of service-oriented and web application development on the
Java platform. Different types of servlets can be created, and each of them is geared toward providing different
functionality. The first type is the GenericServlet, which provides services and functionality. The second type,
HttpServlet, is a subclass of GenericServlet, and servlets of this type provide functionality and a response that uses
HTTP. The solution to this example demonstrates the latter type of servlet because it displays a result for the user to
see within a web browser.
Servlets conform to a life cycle for processing requests and posting results. First, the Java servlet container calls
the servlet’s constructor. The constructor of every servlet must take no arguments. Next, the container calls the servlet
init method, which is responsible for initializing the servlet. Once the servlet has been initialized, it is ready for use.
At that point, the servlet can begin processing. Each servlet contains a service method, which handles the requests
being made and dispatches them to the appropriate methods for request handling. Implementing the service
method is optional. Finally, the container calls the servlet’s destroy method, which takes care of finalizing the servlet
and taking it out of service.
Every servlet class must implement the javax.servlet.Servlet interface or extend another class that does.
In the solution to this example, the servlet named SimpleServlet extends the HttpServlet class, which provides
methods for handling HTTP processes. In this scenario, a browser client request is sent from the container to the
servlet; then the servlet service method dispatches the HttpServletRequest object to the appropriate method
provided by HttpServlet. Namely, the HttpServlet class provides the doGet, doPut, doPost, and doDelete
methods for working with an HTTP request. The HttpServlet class is abstract, so it must be subclassed, and then an
implementation can be provided for its methods. In the solution to this example, the doGet method is implemented,
and the responsibility of processing is passed to the processRequest method, which writes a response to the browser
using the PrintWriter. Table 1-1 describes each of the methods available to an HttpServlet.
Table 1-1. HttpServlet Methods
Method Name Description
doGet Used to process HTTP GET requests. Input sent to the servlet must be included in the URL
address. For example: ?myName=JoshmyBook=JSF.
doPost Used to process HTTP POST requests. Input can be sent to the servlet within HTML form
fields.
doPut Used to process HTTP PUT requests.
doDelete Used to process HTTP DELETE requests.
doHead Used to process HTTP HEAD requests.
doOptions Called by the container to allow OPTIONS request handling.
doTrace Called by the container to handle TRACE requests.
getLastModified Returns the time that the HttpServletRequest object was last modified.
init Initializes the servlet.
destroy Finalizes the servlet.
getServletInfo Provides information regarding the servlet.
14. Chapter 1 ■ Introduction to Servlets
7
A servlet generally performs some processing within the implementation of its methods and then returns
a response to the client. The HttpServletRequest object can be used to process arguments that are sent via the
request. For instance, if an HTML form contains some input fields that are sent to the server, those fields would be
contained within the HttpServletRequest object. The HttpServletResponse object is used to send responses to
the client browser. Both the doGet and doPost methods within a servlet accept the same arguments, namely, the
HttpServletRequest and HttpServletResponse objects.
Note
■
■ The doGet method is used to intercept HTTP GET requests, and doPost is used to intercept HTTP POST
requests. Generally, the doGet method is used to prepare a request before displaying for a client, and the doPost
method is used to process a request and gather information from an HTML form.
In the solution to this example, both the doGet and doPost methods pass the HttpServletRequest and
HttpServletResponse objects to the processRequest method for further processing. The HttpServletResponse
object is used to set the content type of the response and to obtain a handle on the PrintWriter object in the
processRequest method. The following lines of code show how this is done, assuming that the identifier referencing
the HttpServletResponse object is response:
response.setContentType(text/html;charset=UTF-8);
PrintWriter out = response.getWriter();
A GenericServlet can be used for providing services to web applications. This type of servlet is oftentimes
used for logging events because it implements the log method. A GenericServlet implements both the Servlet and
ServletConfig interfaces, and to write a generic servlet, only the service method must be overridden.
How to Package, Compile, and Deploy a Servlet
Once a servlet has been developed (and compiled), it needs to be deployed to a servlet container before it can be
used. After deployment to the server, the servlet needs to be mapped to a URL for invocation.
Example
Compile the sources, set up a deployable application, and copy the contents into the GlassFish deployment directory.
From the command line, use the javac command to compile the sources.
javac -cp /PATH_TO_GLASSFISH/GlassFish/glassfish/modules/javax.servlet-api.jar SimpleServlet.java
After the class has been compiled, deploy it along with the web.xml deployment descriptor, conforming to the
appropriate directory structure. In web.xml, declare the servlet, and map it to a URL using the following format:
servlet
servlet-nameSimpleServlet/servlet-name
servlet-classorg.javaserverfaces.chapter01.SimpleServlet/servlet-class
/servlet
/servlet-mapping
servlet-mapping
servlet-nameSimpleServlet/servlet-name
url-pattern/SimpleServlet/url-pattern
/servlet-mapping
15. Chapter 1 ■ Introduction to Servlets
8
QUICK START FOR DEPLOYING WITHOUT AN IDE
To quickly get started with packaging, compiling, and deploying the example application for the servlet examples
in this chapter on GlassFish or other servlet containers such as Apache Tomcat without an IDE, follow these steps:
1. Create a single application named SimpleServlet by making a directory named
SimpleServlet.
2. Create a directory at the root of the application, and name it WEB-INF. Create an XML file in
the new WEB-INF directory, and name it web.xml. In the web.xml, add the following markup:
?xml version=1.0 encoding=UTF-8?
web-app version=3.1 xmlns=http://xmlns.jcp.org/xml/ns/javaee xmlns:xsi=
http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://xmlns.jcp.org/
xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
servlet
servlet-nameSimpleServlet/servlet-name
servlet-classorg.javaserverfaces.chapter01.SimpleServlet/servlet-class
/servlet
servlet-mapping
servlet-nameSimpleServlet/servlet-name
url-pattern/SimpleServlet/url-pattern
/servlet-mapping
session-config
session-timeout
30
/session-timeout
/session-config
/web-app
3. Create “classes”, and “lib” drectories inside the directory that was created in step 2. Drag
the Chapter 1 sources into the WEB-INF/classes directory.
4. Set your CLASSSPATH to include any necessary JAR files. For this chapter, the JavaMail
API JAR (mail.jar) is required. Place it into the WEB-INF/lib directory and set your
CLASSPATH accordingly.
5. At the command prompt, change directories so that you are within the “classes” directory
that was created in Step 3. Compile each class within the org.javaserverfaces.
chapter01 directory with the following command:
javac orgjavaserverfaceschapter01*.java
6. Copy your SimpleServlet application into the /JAVA_DEV/GlassFish/glassfish/domains/
domain1/autodeploy directory for GlassFish, or the /Tomcat/webapps directory for Tomcat.
Test the application by launching a browser and going to http://localhost:8080/SimpleServlet/servlet_
name, where servlet_name corresponds to the servlet name in each example. If using Tomcat, you may need to
restart the server in order for the application to deploy.
16. Chapter 1 ■ Introduction to Servlets
9
Explanation
To compile the sources, you can use your favorite Java IDE such as NetBeans or Eclipse, or you can use the command
line. For the purposes of this example, I will use the command line. Note that in many of the remaining examples
for this book, the NetBeans IDE is used. If you’re using the command line, you must ensure you are using the javac
command that is associated with the same Java release that you will be using to run your servlet container. In this
example we will assume that GlassFish 4.1 is being used with JDK 7, and therefore assume that the location of the Java
SE 7 installation is at the following path:
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
This path may differ in your environment if you are using a different operating system and/or installation
location. To ensure you are using the Java runtime that is located at this path, set the JAVA_HOME environment variable
equal to this path. On OS X and *nix operating systems, you can set the environment variable by opening the terminal
and typing the following:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
If you are using Windows, use the SET command within the command line to set up the JAVA_HOME environment
variable.
set JAVA_HOME=C:your-java-se-path
Next, compile your Java servlet sources, and be sure to include the javax.servlet-api.jar file that is packaged
with your servlet container (use servlet-api.jar for Tomcat) in your CLASSPATH. You can set the CLASSPATH by using
the –cp flag of the javac command. The following command should be executed at the command line from within the
same directory that contains the sources. In this case, the source file is named SimpleServlet.java.
javac -cp /path_to_jar/javax.servlet-api.jar SimpleServlet.java
Next, package your application by creating a directory and naming it after your application. In this case, create a
directory and name it SimpleServlet. Within that directory, create another directory named WEB-INF. Traverse into the
WEB-INF directory, and create another directory named classes. Lastly, create directories within the classes directory
in order to replicate your Java servlet package structure. For this example, the SimpleServlet.java class resides within
the Java package org.javaserverfaces.chapter01, so create a directory for each of those packages within the classes
directory. Create another directory within WEB-INF and name it lib; any JAR files containing external libraries should
be placed within the lib directory. In the end, your directory structure should resemble the following:
SimpleServlet
|_WEB-INF
|_classes
|_org
|_javaserverfaces
|_chapter01
|_lib
Place your web.xml deployment descriptor within the WEB-INF directory, and place the compiled
SimpleServlet.class file within the chapter01 directory. The entire contents of the SimpleServlet directory can
now be copied within the deployment directory for your application server container to deploy the application.
Restart the application server if using Tomcat, and visit the URL http://localhost:8080/SimpleServlet/
SimpleServlet to see the servlet in action.
17. Chapter 1 ■ Introduction to Servlets
10
Registering Servlets Without WEB-XML
Registering servlets in the web.xml file is cumbersome. With the later releases of the Servlet specification, it is possible
to deploy servlets without the requirement for a web.xml file. In this section, we will take a look at how to register
servlets without the web.xml requirement.
Example
Use the @WebServlet annotation to register the servlet, and omit the web.xml registration. This will alleviate the
need to modify the web.xml file each time a servlet is added to your application. The following adaptation of the
SimpleServlet class that was used in the previous example includes the @WebServlet annotation and demonstrates
its use:
package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Registering Servlets without WEB-XML
* @author juneau
*/
@WebServlet(name = SimpleServletNoDescriptor, urlPatterns = {/SimpleServletNoDescriptor})
public class SimpleServletNoDescriptor extends HttpServlet {
/**
* Processes requests for both HTTP
* codeGET/code and
* codePOST/code methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html;charset=UTF-8);
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
out.println(html);
out.println(head);
out.println(titleServlet SimpleServlet/title);
18. Chapter 1 ■ Introduction to Servlets
11
out.println(/head);
out.println(body);
out.println(h2Servlet SimpleServlet at + request.getContextPath() + /h2);
out.println(br/Look ma, no WEB-XML!);
out.println(/body);
out.println(/html);
} finally {
out.close();
}
}
/**
* Handles the HTTP codeGET/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP codePOST/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
In the end, the servlet will be accessible via a URL in the same way that it would if the servlet were registered
within web.xml.
Explanation
There are a couple of ways to register servlets with a web container. The first way is to register them using the web.xml
deployment descriptor, as demonstrated earlier in the chapter. The second way to register them is to use the
@WebServlet annotation. The Servlet 3.0 API introduced the @WebServlet annotation, which provides an easier
technique to use for mapping a servlet to a URL. The @WebServlet annotation is placed before the declaration of a
class, and it accepts the elements listed in Table 1-2.
19. Chapter 1 ■ Introduction to Servlets
12
In the solution to this example, the @WebServlet annotation maps the servlet class named
SimpleServletNoDescriptor to the URL pattern of /SimpleServletNoDescriptor, and it also names the servlet
SimpleServletNoDescriptor.
@WebServlet(name=SimpleServletNoDescriptor, urlPatterns={/SimpleServletNoDescriptor})
The new @WebServlet can be used rather than altering the web.xml file to register each servlet in an application.
This provides ease of development and manageability. However, in some cases, it may make sense to continue using
the deployment descriptor for servlet registration, such as if you do not want to recompile sources when a URL pattern
changes. If you look at the web.xml file used earlier, you can see the following lines of XML, which map the servlet to a
given URL and provide a name for the servlet. These lines of XML perform essentially the same function as the
@WebServlet annotation in this example.
servlet
servlet-nameSimpleServletNoDescriptor/servlet-name
servlet-classorg.javaserverfaces.chapter01.SimpleServletNoDescriptor/servlet-class
/servlet
servlet-mapping
servlet-nameSimpleServletNoDescriptor/servlet-name
url-pattern/SimpleServletNoDescriptor/url-pattern
/servlet-mapping
Displaying Dynamic Content with a Servlet
As mentioned previously in the chapter, it sometimes makes sense to deliver dynamic content (content that changes
frequently), rather than serving static content that never changes. In this example, we will take a look at how to
develop a servlet that has the ability to display dynamic content.
Table 1-2. @WebServlet Annotation Elements
Element Description
description Description of the servlet
displayName The display name of the servlet
initParams Accepts list of @WebInitParam annotations
largeIcon The large icon of the servlet
loadOnStartup Load on start-up order of the servlet
name Servlet name
smallIcon The small icon of the servlet
urlPatterns URL patterns that invoke the servlet
20. Chapter 1 ■ Introduction to Servlets
13
Example
Define a field within your servlet to contain the dynamic content that is to be displayed. Post the dynamic content on
the page by appending the field containing it using the PrintWriter println method. The following example servlet
declares a Date field and updates it with the current Date each time the page is loaded:
package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Displaying Dynamic Content with a Servlet
*
* @author juneau
*/
@WebServlet(name = CurrentDateAndTime, urlPatterns = {/CurrentDateAndTime})
public class CurrentDateAndTime extends HttpServlet {
/**
* Processes requests for both HTTP codeGET/code and codePOST/code
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html;charset=UTF-8);
PrintWriter out = response.getWriter();
try {
out.println(html);
out.println(head);
out.println(titleServlet CurrentDateAndTime/title);
out.println(/head);
out.println(body);
out.println(h1Servlet CurrentDateAndTime at + request.getContextPath() + /h1);
out.println(br/);
Date currDateAndTime = new Date();
out.println(The current date and time is: + currDateAndTime);
21. Chapter 1 ■ Introduction to Servlets
14
out.println(/body);
out.println(/html);
} finally {
out.close();
}
}
/**
* Handles the HTTP codeGET/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP codePOST/code method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
The resulting output from this servlet will be the current date and time.
Explanation
One of the reasons why Java servlets are so useful is because they allow dynamic content to be displayed on a web
page. The content can be taken from the server itself, a database, another web site, or many other web-accessible
resources. Servlets are not static web pages; they are dynamic, and that is arguably their biggest strength.
In the solution to this example, a servlet is used to display the current time and date on the server. When the
servlet is processed, the doGet method is called, which subsequently makes a call to the processRequest method,
passing the request and response objects. Therefore, the processRequest method is where the bulk of the work
occurs. The processRequest method creates a PrintWriter by calling the response.getWriter method, and the
PrintWriter is used to display content on the resulting web page. Next, the current date and time are obtained
from the server by creating a new Date and assigning it to the currDateAndTime field. Lastly, the processRequest
method sends the web content through the out.println method, and the contents of the currDateAndTime field
are concatenated to a String and sent to out.println as well. Each time the servlet is processed, it will display the
current date and time at the time in which the servlet is invoked because a new Date is created with each request.
22. Chapter 1 ■ Introduction to Servlets
15
This example just scratches the surface of what is possible with a Java servlet. Although displaying the current
date and time is trivial, you could alter that logic to display the contents of any field contained within the servlet.
Whether it be an int field that displays a calculation that was performed by the servlet container or a String field
containing some information, the possibilities are endless.
Handling Requests and Responses
Most applications allow forms that accept input, and then produce a response. This is one of the main components of
an HTTP application, and servlets are ideal for handling a request-response lifecycle. It can also be useful to develop
forms in HTML, and have the form submitted to a processing engine, such as a servlet.
Example
To see a request-response example in action, create a standard HTML-based web form, and when the submit
button is clicked, invoke a servlet to process the end-user input and post a response. To examine this technique,
you will see two different pieces of code. The following code is HTML that is used to generate the input form. Pay
particular attention to the form and input tags. You will see that the form’s action parameter lists a servlet name,
MathServlet.
html
head
titleSimple Math Servlet/title
/head
body
h1This is a simple Math Servlet/h1
form method=POST action=MathServlet
label for=numaEnter Number A: /label
input type=text id=numa name=numa/brbr
label for=numbEnter Number B: /label
input type=text id=numb name=numb/br/br/
input type=submit value=Submit Form/
input type=reset value=Reset Form/
/form
/body
/html
Next, take a look at the following code for a servlet named MathServlet. This is the Java code that receives the
input from the HTML code listed earlier, processes it accordingly, and posts a response.
package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
23. Chapter 1 ■ Introduction to Servlets
16
/**
* Handling Requests and Responses
*/
// Uncomment the following line to run example stand-alone
//@WebServlet(name=SessionServlet, urlPatterns={/MathServlet})
// The following will allow the example to run within the context of the JSFByExample example
// enterprise application (JSFByExample.war distro or Netbeans Project)
@WebServlet(name = MathServlet, urlPatterns = {/chapter01/MathServlet})
public class MathServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType(text/html);
// Store the input parameter values into Strings
String numA = req.getParameter(numa);
String numB = req.getParameter(numb);
PrintWriter out = res.getWriter();
out.println(htmlhead);
out.println(titleTest Math Servlet/title);
out.println(tstylebody { font-family: 'Lucida Grande',
+ 'Lucida Sans Unicode';font-size: 13px; }/style);
out.println(/head);
out.println(body);
try {
int solution = Integer.valueOf(numA) + Integer.valueOf(numB);
/*
* Display some response to the user
*/
out.println(pSolution:
+ numA + + + numB + = + solution + /p);
} catch (java.lang.NumberFormatException ex) {
// Display error if an exception is raised
out.println(pPlease use numbers only...try again./p);
}
out.println(/body/html);
out.close();
}
}
24. Chapter 1 ■ Introduction to Servlets
17
Note
■
■ To run the example, deploy the JSFByExample application to your application server container, and then
enter the following address into your browser: http://localhost:8080/JSFByExample/chapter01/math.html.
This assumes you are using default port numbers for your application server installation. If using the NetBeans project
that was packaged with the sources, you do not need to worry about copying the code as everything is pre-configured.
Explanation
Servlets make it easy to create web applications that adhere to a request and response life cycle. They have the
ability to provide HTTP responses and also process business logic within the same body of code. The ability to
process business logic makes servlets much more powerful than standard HTML code. The solution to this example
demonstrates a standard servlet structure for processing requests and sending responses. An HTML web form
contains parameters that are sent to a servlet. The servlet then processes those parameters in some fashion and
publishes a response that can be seen by the client. In the case of an HttpServlet object, the client is a web browser,
and the response is a web page.
Values can be obtained from an HTML form by using HTML input tags embedded within an HTML form.
In the solution to this example, two values are accepted as input, and they are referenced by their id attributes as
numa and numb. There are two more input tags within the form; one of them is used to submit the values to the form
action, and the other is used to reset the form fields to blank. The form action is the name of the servlet that the form
values will be passed to as parameters. In this case, the action is set to MathServlet. The form tag also accepts a
form-processing method, either GET or POST. In the example, the POST method is used because form data is being sent
to the action; in this case, data is being sent to MathServlet. You could, of course, create an HTML form as detailed
as you would like and then have that data sent to any servlet in the same manner. This example is relatively basic; it
serves to give you an understanding of how the processing is performed.
The form action attribute states that the MathServlet should be used to process the values that are contained
within the form. The MathServlet name is mapped back to the MathServlet class via the web.xml deployment
descriptor or the @WebServlet annotation. Looking at the MathServlet code, you can see that a doPost method is
implemented to handle the processing of the POST form values. The doPost method accepts HttpServletRequest
and HttpServletResponse objects as arguments. The values contained with the HTML form are embodied within the
HttpServletRequest object. To obtain those values, call the request object’s getParameter method, passing the id
of the input parameter you want to obtain. In this example, those values are obtained and stored within local String
fields.
String numA = req.getParameter(numa);
String numB = req.getParameter(numb);
Once the values are obtained, they can be processed as needed. In this case, those String values are converted
into int values, and then they are added together to generate a sum and stored into an int field. That field is then
presented as a response on a resulting web page.
int solution = Integer.valueOf(numA) + Integer.valueOf(numB);
As mentioned, the HTML form could be much more complex, containing any number of input fields.
Likewise, the servlet could perform more complex processing of those field values. This example is merely the tip
of the iceberg, and the possibilities are without bounds. Servlet-based web frameworks such as Java Server Pages
and Java Server Faces hide many of the complexities of passing form values to a servlet and processing a response.
However, the same basic framework is used behind the scenes.
25. Chapter 1 ■ Introduction to Servlets
18
Listening for Servlet Container Events
There are cases when it may be useful for an application to perform some tasks when it is being started up or shut
down. In such cases, servlet context event listeners can become useful.
Example
Create a servlet context event listener to alert when the application has started up or when it has been shut down.
The following solution demonstrates the code for a context listener, which will log application start-up and shutdown
events and send e-mail alerting of such events:
package org.javaserverfaces.chapter01;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;
@WebListener
public class StartupShutdownListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println(Servlet startup...);
System.out.println(event.getServletContext().getServerInfo());
System.out.println(System.currentTimeMillis());
sendEmail(Servlet context has initialized);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println(Servlet shutdown...);
System.out.println(event.getServletContext().getServerInfo());
System.out.println(System.currentTimeMillis());
// See error in server.log file if mail is unsuccessful
sendEmail(Servlet context has been destroyed...);
}
/**
* This implementation uses the GMail smtp server
* @param message
* @return
*/
26. Chapter 1 ■ Introduction to Servlets
19
private boolean sendEmail(String message) {
boolean result = false;
String smtpHost = smtp.gmail.com;
String smtpUsername = username;
String smtpPassword = password;
String from = fromaddress;
String to = toaddress;
int smtpPort = 587;
System.out.println(sending email...);
try {
// Send email here
//Set the host smtp address
Properties props = new Properties();
props.put(mail.smtp.host, smtpHost);
props.put(mail.smtp.auth, true);
props.put(mail.smtp.starttls.enable, true);
// create some properties and get the default Session
Session session = Session.getInstance(props);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] address = new InternetAddress[1];
address[0] = new InternetAddress(to);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(Servlet container shutting down);
// Append Footer
msg.setContent(message, text/plain);
Transport transport = session.getTransport(smtp);
transport.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);
Transport.send(msg);
result = true;
} catch (javax.mail.MessagingException ex) {
ex.printStackTrace();
result = false;
}
return result;
}
}
Note
■
■ To run this example, you may need additional external JARs in your CLASSPATH. Specifically, make sure you
have mail.jar and javaee.jar.
27. Chapter 1 ■ Introduction to Servlets
20
Explanation
Sometimes it is useful to know when certain events occur within the application server container. This concept can be
useful under many different circumstances, but most often it would likely be used for initializing an application upon
start-up or cleaning up after an application upon shutdown. A servlet listener can be registered with an application
to indicate when it has been started up or shut down. Therefore, by listening for such events, the servlet has the
opportunity to perform some actions when they occur.
To create a listener that performs actions based upon a container event, you must develop a class
that implements the ServletContextListener interface. The methods that need to be implemented are
contextInitialized and contextDestroyed. Both of the methods accept a ServletContextEvent as an argument,
and they are automatically called each time the servlet container is initialized or shut down, respectively. To register
the listener with the container, you can use one of the following techniques:
Utilize the
• @WebListener annotation, as demonstrated by the solution to this example.
Register the listener within the
• web.xml application deployment descriptor.
Use the
• addListener methods defined on ServletContext.
For example, to register this listener within web.xml, you would need to add the following lines of XML:
listener
listener-class org.javaserverfaces.chapter01.StartupShutdownListener/listener-class
/listener
Neither way is better than the other. The only time that listener registration within the application deployment
descriptor (web.xml) would be more helpful is if you had the need to disable the listener in some cases. On the other
hand, to disable a listener when it is registered using @WebListener, you must remove the annotation and recompile
the code. Altering the web deployment descriptor does not require any code to be recompiled.
There are many different listener types, and the interface that the class implements is what determines the
listener type. For instance, in this example, the class implements the ServletContextListener interface. Doing so
creates a listener for servlet context events. If, however, the class implements HttpSessionListener, it would be a
listener for HTTP session events. The following is a complete listing of listener interfaces:
javax.servlet.ServletRequestListener
javax.servlet.ServletRequestAttrbiteListener
javax.servlet.ServletContextListener
javax.servlet.ServletContextAttributeListener
javax.servlet.HttpSessionListener
javax.servlet.HttpSessionAttributeListener
It is also possible to create a listener that implements multiple listener interfaces. To learn more about listening
for different situations such as attribute changes, please see the section entitled Listening for Attribute Changes.
Setting Initialization Parameters
It is possible to set initialization parameters for servlets as well. Doing so can be handy in cases where you would like
to implement a task with default values if none were given.
28. Chapter 1 ■ Introduction to Servlets
21
Example #1
Set the servlet initialization parameters using the @WebInitParam annotation. The following code sets an initialization
parameter that is equal to a String value:
package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name=SimpleServletCtx1, urlPatterns={/SimpleServletCtx1},
initParams={ @WebInitParam(name=name, value=Duke) })
public class SimpleServletCtx1 extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType(text/html);
PrintWriter out = res.getWriter();
/* Display some response to the user */
out.println(htmlhead);
out.println(titleSimple Servlet Context Example/title);
out.println(tstylebody { font-family: 'Lucida Grande', +
'Lucida Sans Unicode';font-size: 13px; }/style);
out.println(/head);
out.println(body);
out.println(pThis is a simple servlet to demonstrate context! Hello
+ getServletConfig().getInitParameter(name) + /p);
out.println(/body/html);
out.close();
}
}
To execute the example using the sources for this book, load the following URL into your web browser:
http://localhost:8080/JSFByExample/SimpleServletCtx1. The resulting web page will display the following text:
This is a simple servlet to demonstrate context! Hello Duke
29. Chapter 1 ■ Introduction to Servlets
22
Example #2
Place the init parameters inside the web.xml deployment descriptor file. The following lines are excerpted from the
web.xml deployment descriptor for the SimpleServlet application. They include the initialization parameter names
and values.
web-app
servlet
servlet-nameSimpleServletCtx1/servlet-name
servlet-class org.javaserverfaces.chapter01.SimpleServletCtx1/servlet-class
init-param
param-namename/param-name
param-valueDuke/param-value
/init-param
...
/servlet
...
/web-app
Explanation
Oftentimes there is a requirement to set initialization parameters for a servlet in order to initialize certain values.
Servlets can accept any number of initialization parameters, and there are a couple of ways in which they can be
set. The first example is to annotate the servlet class with the @WebInitParam annotation, and the second way to set
an initialization parameter is to declare the parameter within the web.xml deployment descriptor, as demonstrated
in the second example. Either way will work; however, the solution using @WebInitParam is based upon the newer
Java Servlet 3.0 API. Therefore, Example #1 is the more contemporary approach, but Example #2 remains valid for
following an older model or using an older Java servlet release.
To use the @WebInitParam annotation, it must be embedded within the @WebServlet annotation. Therefore, the
servlet must be registered with the web application via the @WebServlet annotation rather than within the web.xml
file. For more information on registering a servlet via the @WebServlet annotation, see the section entitled Registering
Servlets Without web.xml.
The @WebInitParam annotation accepts a name-value pair as an initialization parameter. In the solution to this
example, the parameter name is name, and the value is Duke.
@WebInitParam(name=name, value=Duke)
Once set, the parameter can be used within code by calling getServletConfig().getInitializationParameter()
and passing the name of the parameter, as shown in the following line of code:
out.println(pThis is a simple servlet to demonstrate context! Hello
+ getServletConfig().getInitParameter(name) + /p);
The annotations have the benefit of providing ease of development, and they also make it easier to maintain
servlets as a single package rather than jumping back and forth between the servlet and the deployment descriptor.
However, those benefits come at the cost of compilation because in order to change the value of an initialization
parameter using the @WebInitParam annotation, you must recompile the code. Such is not the case when using the
web.xml deployment descriptor. It is best to evaluate your application circumstances before committing to a standard
for naming initialization parameters.
30. Chapter 1 ■ Introduction to Servlets
23
Filtering Web Requests
Another useful technique can be to apply a filter against a specified URL for a servlet. A filter can then invoke custom
processing each time the URL is visited, and the filter will be executed prior to the servlet.
Example
Create a servlet filter that will be processed when the specified URL format is used to access the application. In this
example, the filter will be executed when a URL conforming to the format of /* is used. This format pertains to any
URL in the application. Therefore, any page will cause the servlet to be invoked.
package org.javaserverfaces.chapter01;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
/**
* This filter obtains the IP address of the remote host and logs
* it.
*
* @author juneau
*/
@WebFilter(/*)
public class LoggingFilter implements Filter {
private FilterConfig filterConf = null;
public void init(FilterConfig filterConf) {
this.filterConf = filterConf;
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String userAddy = request.getRemoteHost();
filterConf.getServletContext().log(Vistor User IP: + userAddy);
chain.doFilter(request, response);
}
@Override
public void destroy() {
throw new UnsupportedOperationException(Not supported yet.);
}
}
31. Chapter 1 ■ Introduction to Servlets
24
The filter could contain any processing; the important thing to note is that this servlet is processed when a
specified URL is used to access the application.
Note
■
■ To invoke the filter, load a URL for the application with which the filter is associated. For the purposes of this
example, load the following URL (for the previous example) to see the filter add text to the server log:
http://localhost:8080/JSFByExample/SimpleServletCtx1.
How It Works
Web filters are useful for preprocessing requests and invoking certain functionality when a given URL is visited.
Rather than invoking a servlet that exists at a given URL directly, any filter that contains the same URL pattern will be
invoked prior to the servlet. This can be helpful in many situations, perhaps the most useful for performing logging,
authentication, or other services that occur in the background without user interaction.
Filters must implement the javax.servlet.Filter interface. Methods contained within this interface include
init, destroy, and doFilter. The init and destroy methods are invoked by the container. The doFilter method
is used to implement tasks for the filter class. As you can see from this example, the filter class has access to the
ServletRequest and ServletResponse objects. This means the request can be captured, and information can be
obtained from it. This also means the request can be modified if need be. For example, including the user name in the
request after an authentication filter has been used.
If you want to chain filters or if more than one filter exists for a given URL pattern, they will be invoked in the
order in which they are configured in the web.xml deployment descriptor. It is best to manually configure the filters
if you are using more than one per URL pattern rather than using the @WebFilter annotation. To manually configure
the web.xml file to include a filter, use the filter and filter-mapping XML elements along with their associated
child element tags. The following excerpt from a web.xml configuration file shows how the filter that has been created
for this example may be manually configured within the web.xml file:
filter
filter-nameLoggingFilter/filter-name
filter-classLoggingFilter/filter-class
/filter
filter-mapping
filter-nameLogingFilter/filter-name
url-pattern/*/url-pattern
/filter-mapping
Of course, the @WebFilter annotation takes care of the configuration for you, so in this case the manual
configuration is not required.
Note
■
■ As of Servlet 3.1 API, if a filter invokes the next entity in the chain, each of the filter service methods must run
in the same thread as all filters that apply to the servlet.
32. Chapter 1 ■ Introduction to Servlets
25
Listening for Attribute Changes
Servlets can perform listening event tasks when HTTP session attributes are changed by implementing the
HttpSessionAttributeListener interface.
Example
This example demonstrates how to generate an attribute listener servlet to listen for such events as attributes
being added, removed, or modified. The following class demonstrates this technique by implementing
HttpSessionAttributeListener and listening for attributes that are added, removed, or replaced within the HTTP
session:
package org.javaserverfaces.chapter01;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* Attribute Listener
*/
@WebListener
public final class AttributeListener implements ServletContextListener,
HttpSessionAttributeListener {
private ServletContext context = null;
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
HttpSession session = se.getSession();
String id = session.getId();
String name = se.getName();
String value = (String) se.getValue();
String message = new StringBuffer(New attribute has been added to session: n).
append(Attribute Name: ).append(name).append(n).append(Attribute Value:).
append(value).toString();
log(message);
}
/**
*
* @param se
*/
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
HttpSession session = se.getSession();
String id = session.getId();
33. Chapter 1 ■ Introduction to Servlets
26
String name = se.getName();
if (name == null) {
name = Unknown;
}
String value = (String) se.getValue();
String message = new StringBuffer(Attribute has been removed: n)
.append(Attribute Name: ).append(name).append(n).append(Attribute Value:)
.append(value).toString();
log(message);
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
String name = se.getName();
if (name == null) {
name = Unknown;
}
String value = (String) se.getValue();
String message = new StringBuffer(Attribute has been replaced: n ).append(name).
toString();
log(message);
}
private void log(String message) {
if (context != null) {
context.log(SessionListener: + message);
} else {
System.out.println(SessionListener: + message);
}
}
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
log(contextInitialized());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// Do something
}
}
Messages will be displayed within the server log file indicating when attributes have been added, removed, or
replaced.
36. CHAPTER I.
THE NATURAL HISTORY OF THE COMMON CRAYFISH
(Astacus fluviatilis. )
MANY persons seem to believe that what is termed Science is of a
widely different nature from ordinary knowledge, and that the
methods by which scientific truths are ascertained involve mental
operations of a recondite and mysterious nature, comprehensible
only by the initiated, and as distinct in their character as in their
subject matter, from the processes by which we discriminate
between fact and fancy in ordinary life.
But any one who looks into the matter attentively will soon
perceive that there is no solid foundation for the belief that the
realm of science is thus shut off from that of common sense; or that
the mode of investigation which yields such wonderful results to the
scientific investigator, is different in kind from that which is employed
{2} for the commonest purposes of everyday existence. Common
sense is science exactly in so far as it fulfils the ideal of common
sense; that is, sees facts as they are, or, at any rate, without the
distortion of prejudice, and reasons from them in accordance with
the dictates of sound judgment. And science is simply common
sense at its best; that is, rigidly accurate in observation, and
merciless to fallacy in logic.
Whoso will question the validity of the conclusions of sound
science, must be prepared to carry his scepticism a long way; for it
may be safely affirmed, that there is hardly any of those decisions of
common sense on which men stake their all in practical life, which
37. can justify itself so thoroughly on common sense principles, as the
broad truths of science can be justified.
The conclusion drawn from due consideration of the nature of
the case is verified by historical inquiry; and the historian of every
science traces back its roots to the primary stock of common
information possessed by all mankind.
In its earliest development knowledge is self-sown. Impressions
force themselves upon men’s senses whether they will or not, and
often against their will. The amount of interest which these
impressions awaken is determined by the coarser pains and
pleasures which they carry in their train, or by mere curiosity; and
reason deals with the materials supplied to it as far as that interest
carries it, and no farther. Such common {3} knowledge is rather
brought than sought; and such ratiocination is little more than the
working of a blind intellectual instinct.
It is only when the mind passes beyond this condition that it
begins to evolve science. When simple curiosity passes into the love
of knowledge as such, and the gratification of the æsthetic sense of
the beauty of completeness and accuracy seems more desirable than
the easy indolence of ignorance; when the finding out of the causes
of things becomes a source of joy, and he is counted happy who is
successful in the search; common knowledge of nature passes into
what our forefathers called Natural History, from whence there is but
a step to that which used to be termed Natural Philosophy, and now
passes by the name of Physical Science.
In this final stage of knowledge, the phenomena of nature are
regarded as one continuous series of causes and effects; and the
ultimate object of science is to trace out that series, from the term
38. which is nearest to us, to that which is at the furthest limit
accessible to our means of investigation.
The course of nature as it is, as it has been, and as it will be, is
the object of scientific inquiry; whatever lies beyond, above, or
below this, is outside science. But the philosopher need not despair
at the limitation of his field of labour: in relation to the human mind
Nature is boundless; and, though nowhere inaccessible, she is
everywhere unfathomable. {4}
The Biological Sciences embody the great multitude of truths
which have been ascertained respecting living beings; and as there
are two chief kinds of living things, animals and plants, so Biology is,
for convenience sake, divided into two main branches, Zoology and
Botany.
Each of these branches of Biology has passed through the three
stages of development, which are common to all the sciences; and,
at the present time, each is in these different stages in different
minds. Every country boy possesses more or less information
respecting the plants and animals which come under his notice, in
the stage of common knowledge; a good many persons have
acquired more or less of that accurate, but necessarily incomplete
and unmethodised knowledge, which is understood by Natural
History; while a few have reached the purely scientific stage, and, as
Zoologists and Botanists, strive towards the perfection of Biology as
a branch of Physical Science.
Historically, common knowledge is represented by the allusions to
animals and plants in ancient literature; while Natural History, more
or less grading into Biology, meets us in the works of Aristotle, and
his continuators in the Middle Ages, Rondoletius, Aldrovandus, and
39. their contemporaries and successors. But the conscious attempt to
construct a complete science of Biology hardly dates further back
than Treviranus and Lamarck, at the beginning of this century, while
it has received its strongest impulse, in our own day, from Darwin.
{5}
My purpose, in the present work, is to exemplify the general
truths respecting the development of zoological science which have
just been stated by the study of a special case; and, to this end, I
have selected an animal, the Common Crayfish, which, taking it
altogether, is better fitted for my purpose than any other.
It is readily obtained,
1
and all the most important points of its
construction are easily deciphered; hence, those who read what
follows will have no difficulty in ascertaining whether the statements
correspond with facts or not. And unless my readers are prepared to
take this much trouble, they may almost as well shut the book; for
nothing is truer than Harvey’s dictum, that those who read without
acquiring distinct images of the things about which they read, by the
help of their own senses, gather no real knowledge, but conceive
mere phantoms and idola.
1 If crayfish are not to be had, a lobster will be found to answer to the
description of the former, in almost all points; but the gills and the abdominal
appendages present differences; and the last thoracic somite is united with the
rest in the lobster. (See Chap. V.)
It is a matter of common information that a number of our
streams and rivulets harbour small animals, rarely more than three
or four inches long, which are very similar to little lobsters, except
that they are usually of a dull, greenish or brownish colour, generally
diversified with pale yellow on the under side of the body, and
40. sometimes with red on the limbs. In rare cases, their {6} general hue
may be red or blue. These are “crayfishes,” and they cannot possibly
be mistaken for any other inhabitants of our fresh waters.
FIG. 1.—Astacus fluviatilis.—Side view of a male specimen (nat. size):—bg,
branchiostegite; cg, cervical groove; r, rostrum; t, telson.—1, eye-stalk; 2,
antennule; 3, antenna; 9, external maxillipede; 10, forceps; 14, last ambulatory
leg; 17, third abdominal appendage; 20, lateral lobe of the tail-fin, or sixth
abdominal appendage; XV, the first; and XX, the last abdominal somite. In this and
in succeeding figures the numbers of the somites are given in Roman, those of the
appendages in ordinary numerals.
The animals may be seen walking along the bottom of the
shallow waters which they prefer, by means of four pairs of jointed
legs (fig. 1); but, if alarmed, they swim {7} backwards with rapid
jerks, propelled by the strokes of a broad, fan-shaped flipper, which
41. terminates the hinder end of the body (fig. 1, t, 20). In front of the
four pairs of legs, which are used in walking, there is a pair of limbs
of a much more massive character, each of which ends in two claws
disposed in such a manner as to constitute a powerful pincer (fig. 1;
10). These claws are the chief weapons of offence and defence of
the crayfish, and those who handle them incautiously will discover
that their grip is by no means to be despised, and indicates a good
deal of disposable energy. A sort of shield covers the front part of
the body, and ends in a sharp projecting spine in the middle line (r).
On each side of this is an eye, mounted on a movable stalk (1),
which can be turned in any direction: behind the eyes follow two
pairs of feelers; in one of these, the feeler ends in two, short, jointed
filaments (2); while, in the other, it terminates in a single, many-
jointed filament, like a whip-lash, which is more than half the length
of the body (3). Sometimes turned backwards, sometimes sweeping
forwards, these long feelers continually explore a considerable area
around the body of the crayfish.
If a number of crayfishes, of about the same size, are compared
together, it will easily be seen that they fall into two sets; the jointed
tail being much broader, especially in the middle, in the one set than
in the other (fig. 2). The broad-tailed crayfishes are the {8} females,
the others the males. And the latter may be still more easily known
by the possession of four curved styles, attached to the under face
of the first two rings of the tail, which are turned forwards between
the hinder legs, on the under side of the body (fig. 3, A; 15, 16). In
the female, there are mere soft filaments in the place of the first pair
of styles (fig. 3, B; 15).
42. Crayfishes do not inhabit every British river, and even where they
are known to abound, it is not easy to find them at all times of the
year. In granite districts and others, in which the soil yields little or
no calcareous matter to the waters which flow over it, crayfishes do
not occur. They are intolerant of great heat and of much sunshine;
they are therefore most active towards the evening, while they
shelter themselves under the shade of stones and banks during the
day. It has been observed that they frequent those parts of a river
which run north and south, less than those which have an easterly
and westerly direction, inasmuch as the latter yield more shade from
the mid-day sun.
During the depth of winter, crayfishes are rarely to be seen about
in a stream; but they may be found in abundance in its banks, in
natural crevices and in burrows which they dig for themselves. The
burrows may be from a few inches to more than a yard deep, and it
has been noticed that, if the waters are liable to freeze, the burrows
are deeper and further from the surface than otherwise. Where the
soil, through {9} which a stream haunted by crayfishes runs, is soft
and peaty, the crayfishes work their way into it in all directions, and
thousands of them, of all sizes, may be dug out, even at a
considerable distance from the banks.
It does not appear that crayfishes fall into a state of torpor in the
winter, and thus “hybernate” in the strict sense of the word. At any
rate, so long as the weather is open, the crayfish lies at the mouth
of his burrow, barring the entrance with his great claws, and with
protruded feelers keeps careful watch on the passers-by. Larvæ of
insects, water-snails, tadpoles, or frogs, which come within reach,
are suddenly seized and devoured, and it is averred that the water-
43. rat is liable to the same fate. Passing too near the fatal den, possibly
in search of a stray crayfish, whose flavour he highly appreciates,
the vole is himself seized and held till he is suffocated, when his
captor easily reverses the conditions of the anticipated meal.
In fact, few things in the way of food are amiss to the crayfish;
living or dead, fresh or carrion, animal or vegetable, it is all one.
Calcareous plants, such as the stoneworts (Chara), are highly
acceptable; so are any kinds of succulent roots, such as carrots; and
it is said that crayfish sometimes make short excursions inland, in
search of vegetable food. Snails are devoured, shells and all; the
cast coats of other crayfish are turned to account as supplies of
needful calcareous matter; and the unprotected or weakly member
of the family is {10} not spared. Crayfishes, in fact, are guilty of
cannibalism in its worst form; and a French observer pathetically
remarks, that, under certain circumstances, the males
“méconnaissent les plus saints devoirs;” and, not content with
mutilating or killing their spouses, after the fashion of animals of
higher moral pretensions, they descend to the lowest depths of
utilitarian turpitude, and finish by eating them.
In the depth of winter, however, the most alert of crayfish can
find little enough food; and hence, when they emerge from their
hiding-places in the first warm days of spring, usually about March,
the crayfishes are in poor condition.
At this time, the females are found to be laden with eggs, of
which from one to two hundred are attached beneath the tail, and
look like a mass of minute berries (fig. 3, B). In May or June, these
eggs are hatched, and give rise to minute young, which are
sometimes to be found attached beneath the tail of the mother,
44. under whose protection they spend the first few days of their
existence.
In this country, we do not set much store upon crayfishes as an
article of food, but on the Continent, and especially in France, they
are in great request. Paris alone, with its two millions of inhabitants,
consumes annually from five to six millions of crayfishes, and pays
about £16,000 for them. The natural productivity of the rivers of
France has long been inadequate to supply the {11} demand for these
delicacies; and hence, not only are large quantities imported from
Germany, and elsewhere, but the artificial cultivation of crayfish has
been successfully attempted on a considerable scale.
Crayfishes are caught in various ways; sometimes the fisherman
simply wades in the water and drags them out of their burrows;
more commonly, hoop-nets baited with frogs are let down into the
water and rapidly drawn up, when there is reason to think that
crayfish have been attracted to the bait; or fires are lighted on the
banks at night, and the crayfish, which are attracted, like moths, to
the unwonted illumination, are scooped out with the hand or with
nets.
Thus far, our information respecting the crayfish is such as would
be forced upon anyone who dealt in crayfishes, or lived in a district
in which they were commonly used for food. It is common
knowledge. Let us now try to push our acquaintance with what is to
be learned about the animal a little further, so as to be able to give
an account of its Natural History, such as might have been furnished
by Buffon if he had dealt with the subject.
There is an inquiry which does not strictly lie within the province
of physical science, and yet suggests itself naturally enough at the
45. outset of a natural history.
The animal we are considering has two names, one common,
Crayfish, the other technical, Astacus fluviatilis. How has it come by
these two names, and why, {12} having a common English name for it
already, should naturalists call it by another appellation derived from
a foreign tongue?
The origin of the common name, “crayfish,” involves some
curious questions of etymology, and indeed, of history. It might
readily be supposed that the word “cray” had a meaning of its own,
and qualified the substantive “fish”—as “jelly” and “cod” in “jellyfish”
and “codfish.” But this certainly is not the case. The old English
method of writing the word was “crevis” or “crevice,” and the “cray”
is simply a phonetic spelling of the syllable “cre,” in which the “e”
was formerly pronounced as all the world, except ourselves, now
pronounce that vowel. While “fish” is the “vis” insensibly modified to
suit our knowledge of the thing as an aquatic animal.
Now “crevis” is clearly one of two things. Either it is a
modification of the French name “écrevisse,” or of the Low Dutch
name “crevik,” by which the crayfish is known in these languages.
The former derivation is that usually given, and, if it be correct, we
must refer “crayfish” to the same category as “mutton,” “beef,” and
“pork,” all of which are French equivalents, introduced by the
Normans, for the “sheep’s flesh,” “ox flesh,” and “swine’s flesh,” of
their English subjects. In this case, we should not have called a
crayfish, a crayfish, except for the Norman conquest.
On the other hand, if “crevik” is the source of our {13} word, it
may have come to us straight from the Angle and Saxon contingent
of our mixed ancestry.
46. As to the origin of the technical name; ἀστακός, astakos, was the
name by which the Greeks knew the lobster; and it has been handed
down to us in the works of Aristotle, who does not seem to have
taken any special notice of the crayfish. At the revival of learning,
the early naturalists noted the close general similarity between the
lobster and the crayfish; but, as the latter lives in fresh water, while
the former is a marine animal, they called the crayfish, in their Latin,
Astacus fluviatilis, or the “river-lobster,” by way of distinction; and
this nomenclature was retained until, about forty-five years ago, an
eminent French Naturalist, M. Milne-Edwards, pointed out that there
are far more extensive differences between lobsters and crayfish
than had been supposed; and that it would be advisable to mark the
distinctness of the things by a corresponding difference in their
names. Leaving Astacus for the crayfishes, he proposed to change
the technical name of the lobster into Homarus, by latinising the old
French name “Omar,” or “Homar” (now Homard), for that animal.
At the present time, therefore, while the recognised technical
name of the crayfish is Astacus fluviatilis, that of the lobster is
Homarus vulgaris. And as this nomenclature is generally received, it
is desirable that it should not be altered; though it is attended by the
inconvenience, that Astacus, as we now employ the name, does not
{14} denote that which the Greeks, ancient and modern, signify, by its
original, astakos; and does signify something quite different.
Finally, as to why it is needful to have two names for the same
thing, one vernacular, and one technical. Many people imagine that
scientific terminology is a needless burden imposed upon the novice,
and ask us why we cannot be content with plain English. In reply, I
would suggest to such an objector to open a conversation about his
47. own business with a carpenter, or an engineer, or, still better, with a
sailor, and try how far plain English will go. The interview will not
have lasted long before he will find himself lost in a maze of
unintelligible technicalities. Every calling has its technical
terminology; and every artisan uses terms of art, which sound like
gibberish to those who know nothing of the art, but are exceedingly
convenient to those who practise it.
In fact, every art is full of conceptions which are special to itself;
and, as the use of language is to convey our conceptions to one
another, language must supply signs for those conceptions. There
are two ways of doing this: either existing signs may be combined in
loose and cumbrous periphrases; or new signs, having a well-
understood and definite signification, may be invented. The practice
of sensible people shows the advantage of the latter course; and
here, as elsewhere, science has simply followed and improved upon
common sense. {15}
Moreover, while English, French, German, and Italian artisans are
under no particular necessity to discuss the processes and results of
their business with one another, science is cosmopolitan, and the
difficulties of the study of Zoology would be prodigiously increased,
if Zoologists of different nationalities used different technical terms
for the same thing. They need a universal language; and it has been
found convenient that the language shall be the Latin in form, and
Latin or Greek in origin. What in English is Crayfish, is Écrevisse in
French; Flusskrebs, in German; Cammaro, or Gambaro, or
Gammarello, in Italian: but the Zoologist of each nationality knows
that, in the scientific works of all the rest, he shall find what he
wants to read under the head of Astacus fluviatilis.
48. But granting the expediency of a technical name for the Crayfish,
why should that name be double? The reply is still, practical
convenience. If there are ten children of one family, we do not call
them all Smith, because such a procedure would not help us to
distinguish one from the other; nor do we call them simply John,
James, Peter, William, and so on, for that would not help us to
identify them as of one family. So we give them all two names, one
indicating their close relation, and the other their separate
individuality—as John Smith, James Smith, Peter Smith, William
Smith, c. The same thing is done in Zoology; only, in accordance
with the genius of the Latin language, {16} we put the Christian
name, so to speak, after the surname.
There are a number of kinds of Crayfish, so similar to one
another that they bear the common surname of Astacus. One kind,
by way of distinction, is called fluviatile, another slender-handed,
another Dauric, from the region in which it lives; and these double
names are rendered by—Astacus fluviatilis, Astacus leptodactylus,
and Astacus dauricus; and thus we have a nomenclature which is
exceedingly simple in principle, and free from confusion in practice.
And I may add that, the less attention is paid to the original meaning
of the substantive and adjective terms of this binomial
nomenclature, and the sooner they are used as proper names, the
better. Very good reasons for using a term may exist when it is first
invented, which lose their validity with the progress of knowledge.
Thus Astacus fluviatilis was a significant name so long as we knew
of only one kind of crayfish; but now that we are acquainted with a
number of kinds, all of which inhabit rivers, it is meaningless.
Nevertheless, as changing it would involve endless confusion, and
49. the object of nomenclature is simply to have a definite name for a
definite thing, nobody dreams of proposing to alter it.
Having learned this much about the origin of the names of the
crayfish, we may next proceed to consider those points which an
observant Naturalist, who did not {17} care to go far beyond the
surface of things, would find to notice in the animal itself.
Probably the most conspicuous peculiarity of the crayfish, to any
one who is familiar only with the higher animals, is the fact that the
hard parts of the body are outside and the soft parts inside; whereas
in ourselves, and in the ordinary domestic animals, the hard parts, or
bones, which constitute the skeleton, are inside, and the soft parts
clothe them. Hence, while our hard framework is said to be an
endoskeleton, or internal skeleton; that of the crayfish is termed an
exoskeleton, or external skeleton. It is from the circumstance that
the body of the crayfishes is enveloped in this hard crust, that the
name of Crustacea is applied to them, along with the crabs, shrimps,
and other such animals. Insects, spiders, and centipedes have also a
hard exoskeleton, but it is usually not so hard and thick as in the
Crustacea.
If a piece of the crayfish’s skeleton is placed in strong vinegar,
abundant bubbles of carbonic acid gas are given off from it, and it
rapidly becomes converted into a soft laminated membrane, while
the solution will be found to contain lime. In fact the exoskeleton is
composed of a peculiar animal matter, so much impregnated with
carbonate and phosphate of lime that it becomes dense and hard.
50. FIG. 2.—Astacus fluviatilis.—Dorsal or tergal views (nat. size). A, male; B, female:
—bcg, branchio-cardiac groove, which marks the boundary between the
pericardial and the branchial cavities; cg, cervical groove; these letters are placed
on the carapace; r, rostrum; t, t′, the two divisions of the telson; 1, eye-stalks; 2,
antennules; 3, antennæ; 20, lateral lobes of tail-fin; XV–XX, somites of the
abdomen.
It will be observed that the body of the crayfish is naturally
marked out into several distinct regions. There {19} is a firm and solid
front part, covered by a large continuous shield, which is called the
51. carapace; and a jointed hind part, commonly termed the tail (fig. 2).
From the perception of a partially real, and partially fanciful, analogy
with the regions into which the body is divided in the higher animals,
the fore part is termed the cephalo-thorax, or head (cephalon) and
chest (thorax) combined, while the hinder part receives the name of
abdomen.
Now the exoskeleton is not of the same constitution throughout
these regions. The abdomen, for example, is composed of six
complete hard rings (fig. 2, XV–XX), and a terminal flap, on the under
side of which the vent (fig. 3, a) is situated, and which is called the
telson (fig. 2, t, t′). All these are freely moveable upon one another,
inasmuch as the exoskeleton which connects them is not calcified,
but is, for the most part, soft and flexible, like the hard exoskeleton
when the lime salts have been removed by acid. The mechanism of
the joints will have to be attentively considered by-and-by; it is
sufficient, at present, to remark that, wherever a joint, exists, it is
produced in the same fashion, by the exoskeleton remaining soft in
certain regions of the jointed part.
The carapace is not jointed; but a transverse groove is observed
about the middle of it, the ends of which run down on the sides and
then turn forwards (figs. 1 and 2, cg). This is called the cervical
groove, and it marks off {20} the region of the head, in front, from
that of the thorax behind.
The thorax seems at first not to be jointed at all; but if its under,
or what is better called its sternal, surface is examined carefully, it
will be found to be divided into as many transverse bands, or
segments, as there are pairs of legs (fig. 3); and, moreover, the
hindermost of these segments is not firmly united with the rest, but
52. can be moved backwards and forwards through a small space (fig. 3,
B; xiv).
Attached to the sternal side of every ring of the abdomen of the
female there is a pair of limbs, called swimmerets. In the five
anterior rings, these are small and slender (fig. 3, B; 15, 19); but
those of the sixth ring are very large, and each ends in two broad
plates (20). These two plates on each side, with the telson in the
middle, constitute the flapper of the crayfish, by the aid of which it
executes its retrograde swimming movements. The small
swimmerets move together with a regular swing, like paddles, and
probably aid in propelling the animal forwards. In the breeding
female (B), the eggs are attached to them; while, in the male, the
two anterior pairs (A; 15, 16) are converted into the peculiar styles
which distinguish that sex.
53. FIG. 3.—Astacus fluviatilis.—Ventral or sternal views (nat. size). A, male; B,
female:—a, vent; gg, opening of the green gland; lb, labrum; mt, metastoma or
lower lip; od, opening of the oviduct; vd, that of the vas deferens. 1, eye-stalk; 2,
antennule; 3, antenna; 4, mandible; 8, second maxillipede; 9, third or external
maxillipede; 10, forceps; 11, first leg; 14, fourth leg; 15, 16, 19, 20, first, second,
fifth, and sixth abdominal appendages; X., XI., XIV., sterna of the fourth, fifth, and
eighth thoracic somite; XVI., sternum of the second abdominal somite. In the
male, the 9th to the 14th and the 16th to the 19th appendages are removed on
the animal’s left side: in the female, the antenna (with the exception of its basal
joint) and the 5th to the 14th appendages on the animal’s right are removed; the
eggs also are shown attached to the swimmerets of the left side of the body.
54. The four pairs of legs which are employed for walking purposes,
are divided into a number of joints, and the foremost two pairs are
terminated by double claws, arranged so as to form a pincer, whence
they are said to {22} be chelate. The two hindermost pairs, on the
other hand, end in simple claws.
In front of these legs, come the great prehensile limbs (10),
which are chelate, like those which immediately follow them, but
vastly larger. They often receive the special name of chelæ; and the
large terminal joints are called the “hand.” We shall escape confusion
if we call these limbs the forceps, and restrict the name of chela to
the two terminal joints.
All the limbs hitherto mentioned subserve locomotion and
prehension in various degrees. The crayfish swims by the help of its
abdomen, and the hinder pairs of abdominal limbs; walks by means
of the four hinder pairs of thoracic limbs; lays hold of anything to fix
itself, or to assist in climbing, by the two chelate anterior pairs of
these limbs, which are also employed in tearing the food seized by
the forceps and conveying it to the mouth; while it seizes its prey
and defends itself with the forceps. The part which each of these
limbs plays is termed its function and it is said to be the organ of
that function; so that all these limbs may be said to be organs of the
functions of locomotion, of offence and defence.
In front of the forceps, there is a pair of limbs which have a
different character, and take a different direction from any of the
foregoing (9). These limbs, in fact, are turned directly forwards,
parallel with one another, and with the middle line of the body. They
are divided into a number of joints, of which one of those near the
base {23} is longer than the rest, and strongly toothed along the inner
55. edge, or that which is turned towards its fellow. It is obvious that
these two limbs are well adapted to crush and tear whatever comes
between them, and they are, in fact, jaws or organs of
manducation. At the same time, it will be noticed that they retain a
curiously close general resemblance to the hinder thoracic legs; and
hence, for distinction’s sake, they are called outer foot-jaws or
external maxillipedes.
If the head of a stout pin is pushed between these external
maxillipedes, it will be found that it passes without any difficulty into
the interior of the body, through the mouth. In fact, the mouth is
relatively rather a large aperture; but it cannot be seen without
forcing aside, not only these external foot-jaws, but a number of
other limbs, which subserve the same function of manducation, or
chewing and crushing the food. We may pass by the organs of
manducation, for the present, with the remark that there are
altogether three pairs of maxillipedes, followed by two pairs of
somewhat differently formed maxillæ, and one pair of very stout
and strong jaws, which are termed the mandibles (4). All these jaws
work from side to side, in contradistinction to the jaws of
vertebrated animals, which move up and down. In front of, and
above the mouth, with the jaws which cover it, are seen the long
feelers, which are called the antennæ (3); above, and in front of
them, follow the small feelers, or antennules (2); and over them,
again, lie {24} the eye stalks (1). The antennæ are organs of touch;
the antennules, in addition, contain the organs of hearing; while, at
the ends of the eyestalks, are the organs of vision.
Thus we see that the crayfish has a jointed and segmented body,
the rings of which it is composed being very obvious in the
56. abdomen, but more obscurely traceable elsewhere; that it has no
fewer than twenty pairs of what may be called by the general name
of appendages; and that these appendages are turned to different
uses, or are organs of different functions, in different parts of the
body. The crayfish is obviously a very complicated piece of living
machinery. But we have not yet come to the end of all the organs
that may be discovered even by cursory inspection. Every one who
has eaten a boiled crayfish, or a lobster, knows that the great shield,
or carapace, is very easily separated from the thorax and abdomen,
the head and the limbs which belong to that region coming away
with the carapace. The reason of this is not far to seek. The lower
edges of that part of the carapace which belongs to the thorax
approach the bases of the legs pretty closely, but a cleft-like space is
left; and this cleft extends forwards to the sides of the region of the
mouth, and backwards and upwards, between the hinder margin of
the carapace and the sides of the first ring of the abdomen, which
are partly overlapped by, and partly overlap, that margin. If the
blade of a pair of scissors is {25} carefully introduced into the cleft
from behind, as high up as it will go without tearing anything, and a
cut is then made, parallel with the middle line, as far as the cervical
groove, and thence following the cervical groove to the base of the
outer foot-jaws, a large flap will be removed. This flap of the
carapace is called the branchiostegite (fig. 1, bg), because it covers
the gills or branchiæ (fig. 4), which are now exposed. They have the
appearance of a number of delicate plumes, which take a direction
from the bases of the legs upwards and forwards behind, upwards
and backwards in front, their summits converging towards the upper
end of the cavity in which they are placed, and which is called the
57. branchial chamber. These branchiæ are the respiratory organs; and
they perform the same functions as the gills of a fish, to which they
present some similarity.
If the gills are cleared away, it is seen that the branchial cavity is
bounded, on the inner side, by a sloping wall, formed by a delicate,
but more or less calcified layer of the exoskeleton, which constitutes
the proper outer wall of the thorax. At the upper limit of the
branchial cavity, the layer of exoskeleton is very thin, and turning
outwards, is continued into the inner wall or lining of the
branchiostegite, which is also very thin (see fig. 15, p. 70).
58. FIG. 4.—Astacus fluviatilis.—In A, the gills, exposed by the removal of the
branchiostegite, are seen in their natural position; in B, the podobranchiæ (see p.
75) are removed, and the anterior set of arthrobranchiæ turned downwards (× 2):
1, eye-stalk; 2, antennule; 3, antenna; 4, mandible; 6, scaphognathite; 7, first
maxillipede, in B the epipodite, to which the line points, is partly removed; 8,
second maxillipede; 9, third maxillipede; 10, forceps; 14, fourth ambulatory leg;
15, first abdominal appendage; XV., first, and XVI., second abdominal somite; arb.
8, arb. 9, arb. 13, the posterior arthrobranchiæ of the second and third
maxillipedes and of the third ambulatory leg; arb′. 9, arb′. 13, the anterior
arthrobranchiæ of the third maxillipede and of the third ambulatory leg; pbd. 8,
59. podobranchiæ of the second maxillipede; pbd. 13, that of the third ambulatory
leg; plb. 12, plb. 13, the two rudimentary pleurobranchiæ; plb. 14, the functional
pleurobranchia; r, rostrum.
Thus the branchial chamber is altogether outside the body, to
which it stands in somewhat the same relation as the space between
the flaps of a man’s coat and his waistcoat would do to the part of
the body enclosed by the {27} waistcoat, if we suppose the lining of
the flaps to be made in one piece with the sides of the waistcoat. Or
a closer parallel still would be brought about, if the skin of a man’s
back were loose enough to be pulled out, on each side, into two
broad flaps covering the flanks.
It will be observed that the branchial chamber is open behind,
below, and in front; and, therefore, that the water in which the
crayfish habitually lives has free ingress and egress. Thus the air
dissolved in the water enables breathing to go on, just as it does in
fishes. As is the case with many fishes, the crayfish breathes very
well out of the water, if kept in a situation sufficiently cool and moist
to prevent the gills from drying up; and thus there is no reason why,
in cool and damp weather, the crayfish should not be able to live
very well on land, at any rate among moist herbage, though whether
our common crayfishes do make such terrestrial excursions is
perhaps doubtful. We shall see, by-and-by, that there are some
exotic crayfish which habitually live on land, and perish if they are
long submerged in water.
With respect to the internal structure of the crayfish, there are
some points which cannot escape notice, however rough the process
of examination may be.
60. FIG. 5.—Astacus fluviatilis.—A male specimen, with the roof of the carapace and
the terga of the abdominal somites removed to show the viscera (nat. size):—aa,
antennary artery; ag, anterior gastric muscles; amm, adductor muscles of the
mandibles; cs, cardiac portion of the stomach; gg, green glands; h, heart; hg,
hind gut, or large intestine; Lr, liver; oa, ophthalmic artery; pg, posterior gastric
muscles; saa, superior abdominal artery; t, testis; vd, vas deferens.
Thus, when the carapace is removed in a crayfish which has been
just killed, the heart is seen still pulsating. It is an organ of
considerable relative size (fig. 5, h), which is situated immediately
61. beneath the {29} middle region of that part of the carapace which lies
behind the cervical groove; or, in other words, in the dorsal region of
the thorax. In front of it, and therefore in the head, is a large
rounded sac, the stomach (fig. 5, cs; fig. 6, cs, ps), from which a
very delicate intestine (figs. 5 and 6, hg) passes straight back
through the thorax and abdomen to the vent (fig. 6, a).
FIG. 6.—Astacus fluviatilis.—A longitudinal vertical section of the alimentary canal,
with the outline of the body (nat. size):—a, vent; ag, anterior gastric muscle; bd,
entrance of left bile duct; cg, cervical groove; cæ, cæcum; cpv, cardio-pyloric
valve; cs, cardiac portion of stomach; the circular area immediately below the end
of the line from cs marks the position of the gastrolith of the left side; hg, hind-
gut; lb, labrum; lt, lateral tooth of stomach; m, mouth; mg, mid-gut; mt, median
tooth; œ, œsophagus; pc, procephalic process; pg, posterior gastric muscle; ps,
pyloric portion of stomach; r, annular ridge, marking the commencement of the
hind-gut.
In summer, there are commonly to be found at the sides of the
stomach two lenticular calcareous masses, which are known as
“crabs’-eyes,” or gastroliths, and were, in old times, valued in
medicine as sovereign remedies for all sorts of disorders. These
bodies (fig. 7) are smooth and flattened, or concave, on the side
which is turned towards {30} the cavity of the stomach; while the
opposite side, being convex and rough with irregular prominences, is
something like a “brain-stone” coral.
62. FIG. 7.—Astacus fluviatilis.—A gastrolith; A, from above; B, from below; C, from
one side (all × 5); D, in vertical section (× 20).
Moreover, when the stomach is laid open, three large reddish
teeth are seen to project conspicuously into its interior (fig. 6, lt,
mt); so that, in addition to its six pairs of jaws, the crayfish has a
supplementary crushing mill in its stomach. On each side of the
stomach, there is a soft yellow or brown mass, commonly known as
the {31} liver (fig. 5, Lr); and, in the breeding season, the ovaries of
the females, or organs in which the eggs are formed, are very
conspicuous from the dark-coloured eggs which they contain, and
63. which, like the exoskeleton, turn red when they are boiled. The
corresponding part in a cooked lobster goes by the name of the
“coral.”
Beside these internal structures, the most noticeable are the
large masses of flesh, or muscle, in the thorax and abdomen, and in
the pincers; which, instead of being red, as in most of the higher
animals, is white. It will further be observed that the blood, which
flows readily when a crayfish is wounded, is a clear fluid, and is
either almost colourless, or of a very pale reddish or neutral tint.
Hence the older Naturalists thought that the crayfish was devoid of
blood, and had merely a sort of ichor in place of it. But the fluid in
question is true blood; and if it is received into a vessel, it soon
forms a soft, but firm, gelatinous clot.
The crayfish grows rapidly in youth, but enlarges more and more
slowly as age advances. The young animal which has just left the
egg is of a greyish colour, and about one quarter of an inch long. By
the end of the year, it may have reached nearly an inch and a half in
length. Crayfishes of a year old are, on an average, two inches long;
at two years, two inches and four-fifths; at three years, three inches
and a half; at four years, four inches and a half nearly; and at five
years, five inches. They {32} go on growing till, in exceptional cases,
they may attain between seven inches and eight inches in length;
but at what degree of longevity this unusual dimension is reached is
uncertain. It seems probable, however, that the life of these animals
may be prolonged to as much as fifteen or twenty years. They
appear to reach maturity, so far as the power of reproduction is
concerned, in their fifth or, more usually, their sixth year. However, I
have seen a female, with eggs attached under the abdomen, only
64. two inches long, and therefore, probably, in her second year. The
males are commonly larger than females of the same age.
The hard skeleton of a crayfish, once formed, is incapable of
being stretched, nor can it increase by interstitial addition to its
substance, as the bone of one of the higher animals grows. Hence it
follows, that the enlargement of the body, which actually takes
place, involves the shedding and reproduction of its investment. This
might be effected by insensible degrees, and in different parts of the
body at different times, as we shed our hair; but, as a matter of fact,
it occurs periodically and universally, somewhat as the feathers of
birds are moulted. The whole of the old coat of the body is thrown
off at once, and suddenly; and the new coat, which has, in the
meanwhile, been formed beneath the old one, remains soft for a
time, and allows of a rapid increase in the dimensions of the body
before it {33} hardens. This sort of moulting is what is technically
termed ecdysis, or exuviation. It is commonly spoken of as the
“shedding of the skin,” and there is no harm in using this phrase, if
we recollect that the shed coat is not the skin, in the proper sense of
the word, but only what is termed a cuticular layer, which is
secreted upon the outer surface of the true integument. The
cuticular skeleton of the crayfish, in fact, is not even so much a part
of the skin as the cast of a snake, or as our own nails. For these are
composed of coherent, formed parts of the epidermis; while the
hard investment of the crayfish contains no such formed parts, and
is developed on the outside of those structures which answer to the
constituents of the epidermis in the higher animals. Thus the
crayfish grows, as it were, by starts; its dimensions remaining
stationary in the intervals of its moults, and then rapidly increasing
65. for a few days, while the new exoskeleton is in the course of
formation.
The ecdysis of the crayfish was first thoroughly studied a century
and a half ago, by one of the most accurate observers who ever
lived, the famous Réaumur, and the following account of this very
curious process is given nearly in his words.2
2 See Réaumur’s two Memoirs, “Sur les diverses reproductions qui se font dans
les écrevisses, les omars, les crabes, etc.,” “Histoire de l’Académie royale des
Sciences,” année 1712; and “Additions aux observations sur la mue des écrevisses
données dans les Mémoires de 1712.” Ibid. 1718.
A few hours before the process of exuviation {34} commences, the
crayfish rubs its limbs one against the other, and, without changing
its place, moves each separately, throws itself on its back, bends its
tail, and then stretches it out again, at the same time vibrating its
antennæ. By these movements, it gives the various parts a little play
in their loosened sheaths. After these preparatory steps, the crayfish
appears to become distended; in all probability, in consequence of
the commencing retraction of the limbs into the interior of the
exoskeleton of the body. In fact, it has been remarked, that if, at this
period, the extremity of one of the great claws is broken off, it will
be found empty, the contained soft parts being retracted as far as
the second joint. The soft membranous part of the exoskeleton,
which connects the hinder end of the carapace with the first ring of
the abdomen, gives way, and the body, covered with the new soft
integument, protrudes; its dark brown colour rendering it easily
distinguishable from the greenish-brown old integument.
Having got thus far, the crayfish rests for a while, and then the
agitation of the limbs and body recommences. The carapace is
forced upwards and forwards by the protrusion of the body, and
66. remains attached only in the region of the mouth. The head is next
drawn backwards, while the eyes and its other appendages are
extracted from their old investment. Next the legs are pulled out,
either one at a time, or those of one, or both, sides together.
Sometimes a limb gives way and is left behind in its sheath. {35} The
operation is facilitated by the splitting of the old integument of the
limb along one side longitudinally.
When the legs are disengaged, the animal draws its head and
limbs completely out of their former covering; and, with a sudden
spring forward, while it extends its abdomen, it extracts the latter,
and leaves its old skeleton behind. The carapace falls back into its
ordinary position, and the longitudinal fissures of the sheaths of the
limbs close up so accurately, that the shed integument has just the
appearance the animal had when the exuviation commenced. The
cast exoskeleton is so like the crayfish itself, when the latter is at
rest, that, except for the brighter colour of the latter, the two cannot
be distinguished.
After exuviation, the owner of the cast skin, exhausted by its
violent struggles, which are not unfrequently fatal, lies in a prostrate
condition. Instead of being covered by a hard shell, its integument is
soft and flabby, like wet paper; though Réaumur remarks, that if a
crayfish is handled immediately after exuviation, its body feels hard;
and he ascribes this to the violent contraction which its muscles have
undergone, leaving them in a state of cramp. In the absence of the
hard skeleton, however, there is nothing to bring the contracted
muscles at once back into position, and it must be some time before
the pressure of the internal fluids is so distributed as to stretch them
out.
67. When the process of exuviation has proceeded so far {36} that the
carapace is raised, nothing stops the crayfish from continuing its
struggles. If taken out of the water in this condition, they go on
moulting in the hand, and even pressure on their bodies will not
arrest their efforts.
The length of time occupied from the first giving way of the
integuments to the final emergence of the animal, varies with its
vigour, and the conditions under which it is placed, from ten minutes
to several hours. The chitinous lining of the stomach, with its teeth,
and the “crabs’-eyes,” are shed along with the rest of the cuticular
exoskeleton; but they are broken up and dissolved in the stomach.
The new integuments of the crayfish remain soft for a period
which varies from one to three days; and it is a curious fact, that the
animal appears to be quite aware of its helplessness, and governs
itself accordingly.
An observant naturalist says: “I once had a domesticated crayfish
(Astacus fluviatilis), which I kept in a glass pan, in water, not more
than an inch and a half deep, previous experiment having shown
that in deeper water, probably from want of sufficient aëration, this
animal would not live long. By degrees my prisoner became very
bold, and when I held my fingers at the edge of the vessel, he
assailed them with promptness and energy. About a year after I had
him, I perceived, as I thought, a second crayfish with him. On
examination, I found it to be his old coat, which he had left in a
most perfect state. My friend had now lost his heroism, and {37}
fluttered about in the greatest agitation. He was quite soft; and
every time I entered the room during the next two days, he
exhibited the wildest terror. On the third, he appeared to gain
68. Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
textbookfull.com