Visit https://ebookfinal.
com to download the full version and
explore more ebook
Servlet and JSP a tutorial 2nd edition Edition
Kurniawan
_____ Click the link below to download _____
https://ebookfinal.com/download/servlet-and-jsp-a-
tutorial-2nd-edition-edition-kurniawan/
Explore and download more ebook at ebookfinal.com
Here are some recommended products that might interest you.
You can download now and explore!
Murach s Java Servlets and JSP 2nd Edition Andrea Steelman
https://ebookfinal.com/download/murach-s-java-servlets-and-jsp-2nd-
edition-andrea-steelman/
ebookfinal.com
Beginning JSP JSF and Tomcat Java Web Development 2nd
Edition Giulio Zambon
https://ebookfinal.com/download/beginning-jsp-jsf-and-tomcat-java-web-
development-2nd-edition-giulio-zambon/
ebookfinal.com
Java Servlet Programming Second Edition Jason Hunter
https://ebookfinal.com/download/java-servlet-programming-second-
edition-jason-hunter/
ebookfinal.com
JSP Examples and Best Practices 1st Edition Andrew Patzer
https://ebookfinal.com/download/jsp-examples-and-best-practices-1st-
edition-andrew-patzer/
ebookfinal.com
The Java EE 5 Tutorial 2nd ed Edition Eric Jendrock
https://ebookfinal.com/download/the-java-ee-5-tutorial-2nd-ed-edition-
eric-jendrock/
ebookfinal.com
XML XSLT Java and JSP A Case Study in Developing a Web
Application 1st ed Edition Rockwell
https://ebookfinal.com/download/xml-xslt-java-and-jsp-a-case-study-in-
developing-a-web-application-1st-ed-edition-rockwell/
ebookfinal.com
Independent Component Analysis A Tutorial Introduction
James V. Stone
https://ebookfinal.com/download/independent-component-analysis-a-
tutorial-introduction-james-v-stone/
ebookfinal.com
Information Theory A Tutorial Introduction 1st Edition
James V. Stone
https://ebookfinal.com/download/information-theory-a-tutorial-
introduction-1st-edition-james-v-stone/
ebookfinal.com
A tutorial on elliptic PDE solvers and their
parallelization Craig C. Douglas
https://ebookfinal.com/download/a-tutorial-on-elliptic-pde-solvers-
and-their-parallelization-craig-c-douglas/
ebookfinal.com
Servlet and JSP a tutorial 2nd edition Edition Kurniawan
Digital Instant Download
Author(s): Kurniawan, Budi
ISBN(s): 9781771970280, 1771970286
Edition: 2nd edition
File Details: PDF, 5.84 MB
Year: 2015
Language: english
Servlet & JSP
A Tutorial
Second Edition
Budi Kurniawan
Servlet & JSP: A Tutorial, Second Edition
Copyright © 2015 by Brainy Software Inc.
Cover image © rudi1976 / Dollar Photo Club
First Edition: November 2015
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information storage
and retrieval system, without written permission from the publisher, except for the inclusion of
brief quotations in a review.
ISBN: 9781771970273
Book and Cover Designer: Brainy Software Team
Technical Reviewer: Paul Deck
Indexer: Chris Mayle
Trademarks
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
UNIX is a registered trademark of The Open Group.
Microsoft Internet Explorer is either a registered trademark or a trademark of Microsoft
Corporation in The United States and/or other countries.
Apache is a trademark of The Apache Software Foundation.
Firefox is a registered trademark of the Mozilla Foundation.
Google is a trademark of Google, Inc.
Throughout this book the printing of trademarked names without the trademark symbol is for
editorial purpose only. We have no intention of infringement of the trademark.
Warning and Disclaimer
Every effort has been made to make this book as accurate as possible. The author and the publisher
shall have neither liability nor responsibility to any person or entity with respect to any loss or
damages arising from the information in this book.
About the Author
Known for his clear writing style, Budi has been writing programming books for more
than 15 years. His Java tutorial book was recently selected by a team of computer science
professors at HDM Stuttgart, Germany as the main text for the university following a
thorough evaluation of his and similar titles.
His writing is backed by his 20 years of experience as a software architect and
developer. He has been a consultant for various organizations around the world, from a
phone maker in Finland to investment banks in the UK and start-ups in the US and
Canada.
Budi has also written commercial software like the web-based document management
CreateData and is currently writing a research Java Virtual Machine. His other books
include How Tomcat Works, Servlet & JSP: A Tutorial and Struts 2 Design and
Programming.
Table of Contents
Introduction.......................................................................................................................1
Servlet/JSP Application Architecture.............................................................................2
The Hypertext Transfer Protocol (HTTP)......................................................................3
About This Book............................................................................................................7
Downloading the Sample Applications..........................................................................9
Choosing a Framework..................................................................................................9
Chapter 1: Getting Started.............................................................................................11
Downloading and Installing NetBeans.........................................................................11
Creating A Web Project with NetBeans.......................................................................20
Troubleshooting...........................................................................................................26
Creating A Servlet........................................................................................................26
Behind the Scenes........................................................................................................31
Starting, Stopping and Restarting Tomcat....................................................................32
Monitoring HTTP Traffic............................................................................................34
Summary......................................................................................................................34
Chapter 2: The Servlet API............................................................................................37
Servlet API Overview..................................................................................................37
Servlet..........................................................................................................................38
Writing A Basic Servlet Application............................................................................39
ServletRequest.............................................................................................................42
ServletResponse...........................................................................................................43
ServletConfig...............................................................................................................44
ServletContext.............................................................................................................46
GenericServlet.............................................................................................................47
HTTP Servlets..............................................................................................................49
HttpServletRequest......................................................................................................50
Working with HTML Forms........................................................................................51
Using the Deployment Descriptor................................................................................57
Summary......................................................................................................................60
Chapter 3: Session Management....................................................................................61
Hidden Fields...............................................................................................................66
Cookies........................................................................................................................71
HttpSession Objects.....................................................................................................79
Notifying the Browser the HttpSession Has Expired...................................................88
Summary......................................................................................................................89
vi Servlet & JSP: A Tutorial, Second Edition
Chapter 4: JavaServer Pages.........................................................................................91
An Overview of JSP.....................................................................................................91
Comments....................................................................................................................96
Implicit Objects............................................................................................................96
Directives.....................................................................................................................99
Scripting Elements.....................................................................................................102
Summary....................................................................................................................110
Chapter 5: The Expression Language.........................................................................111
A Brief History of the Expression Language.............................................................111
The Expression Language Syntax..............................................................................111
Accessing JavaBeans.................................................................................................114
EL Implicit Objects....................................................................................................114
Using Other EL Operators.........................................................................................118
Referencing Static Fields and Methods......................................................................120
Creating Sets, Lists and Maps....................................................................................121
Accessing List Elements and Map Entries.................................................................122
Manipulating Collections...........................................................................................122
Formatting Collections...............................................................................................125
Formatting Numbers..................................................................................................127
Formatting Dates........................................................................................................128
Configuring the EL in JSP 2.0 and Later Versions.....................................................128
Summary....................................................................................................................130
Chapter 6: JSTL...........................................................................................................131
Downloading JSTL....................................................................................................131
JSTL Libraries...........................................................................................................131
General-Purpose Actions...........................................................................................132
Conditional Actions...................................................................................................139
Iterator Actions..........................................................................................................141
Formatting Actions....................................................................................................151
Functions....................................................................................................................158
Summary....................................................................................................................162
Chapter 7: Writing Custom Tags................................................................................165
Custom Tag Overview...............................................................................................165
Simple Tag Handlers..................................................................................................166
SimpleTag Example...................................................................................................166
Handling Attributes....................................................................................................169
Manipulating the Tag Body.......................................................................................172
Writing EL Functions.................................................................................................174
Distributing Custom Tags..........................................................................................176
Summary....................................................................................................................177
Chapter 8: Tag Files.....................................................................................................179
Introduction to Tag Files............................................................................................179
Your First Tag File.....................................................................................................180
Tag File Directives.....................................................................................................181
doBody.......................................................................................................................189
Table of Contents vii
invoke........................................................................................................................192
Summary....................................................................................................................194
Chapter 9: Listeners.....................................................................................................195
Listener Interfaces and Registration...........................................................................195
Servlet Context Listeners...........................................................................................196
Session Listeners........................................................................................................198
ServletRequest Listeners............................................................................................203
Summary....................................................................................................................205
Chapter 10: Filters........................................................................................................207
The Filter API............................................................................................................207
Filter Configuration...................................................................................................208
Example 1: Logging Filter.........................................................................................210
Example 2: Image Protector Filter.............................................................................214
Example 3: Download Counter Filter.........................................................................215
Filter Order................................................................................................................219
Summary....................................................................................................................219
Chapter 11: Application Design...................................................................................221
Model 1 Overview.....................................................................................................221
Model 2 Overview.....................................................................................................221
Model 2 with A Servlet Controller.............................................................................223
Model 2 with A Filter Dispatcher...............................................................................232
Validators...................................................................................................................235
Dependency Injection................................................................................................241
Summary....................................................................................................................247
Chapter 12: File Upload...............................................................................................249
Client Side Programming...........................................................................................249
Server Side Programming..........................................................................................250
Upload Servlet Example............................................................................................251
Multiple Uploads.......................................................................................................254
Upload Clients...........................................................................................................257
Summary....................................................................................................................262
Chapter 13: File Download...........................................................................................265
File Download Overview...........................................................................................265
Example 1: Hiding A Resource..................................................................................266
Example 2: Preventing Cross-Referencing.................................................................270
Summary....................................................................................................................273
Chapter 14: Java Database Connectivity....................................................................275
Introduction to JDBC.................................................................................................275
Four Steps to Data Access..........................................................................................276
Using Java DB...........................................................................................................282
Obtaining Auto-Generated Keys................................................................................284
Managing Databases with NetBeans..........................................................................285
The Data Access Object (DAO) Pattern.....................................................................287
Connection Pooling....................................................................................................292
Servlet Meets JDBC...................................................................................................294
viii Servlet & JSP: A Tutorial, Second Edition
Reading the Metadata.................................................................................................306
Summary....................................................................................................................311
Chapter 15: Java Persistence API................................................................................313
JPA Overview............................................................................................................313
Creating Entities.........................................................................................................314
Managing Entities......................................................................................................317
Working with Queries................................................................................................320
Using NetBeans to Deal with JPA.............................................................................320
Servlet Meets JPA......................................................................................................326
Summary....................................................................................................................340
Chapter 16: JavaMail...................................................................................................341
JavaMail Overview....................................................................................................341
Sending Emails with JavaMail...................................................................................342
Sending Emails with Apache Commons Email..........................................................344
Using Gmail’s SMTP Server......................................................................................345
WebMail....................................................................................................................346
Summary....................................................................................................................371
Chapter 17: Decorating Requests and Responses.......................................................373
The Decorator Pattern................................................................................................373
Servlet Wrapper Classes............................................................................................375
Example: AutoCorrect Filter......................................................................................375
Summary....................................................................................................................382
Chapter 18: Asynchronous Processing........................................................................383
Overview....................................................................................................................383
Writing Async Servlets and Filters............................................................................383
Writing Async Servlets..............................................................................................384
Async Listeners..........................................................................................................389
ReadListener..............................................................................................................391
WriteListener.............................................................................................................395
Summary....................................................................................................................398
Chapter 19: Security.....................................................................................................399
Authentication and Authorization..............................................................................399
Authentication Methods.............................................................................................403
SSL and TLS..............................................................................................................410
Programmatic Security...............................................................................................415
Summary....................................................................................................................418
Chapter 20: Deployment...............................................................................................419
Deployment Descriptor Overview..............................................................................419
Deployment................................................................................................................431
Web Fragments..........................................................................................................431
Summary....................................................................................................................433
Chapter 21: WebSocket...............................................................................................435
WebSocket Overview................................................................................................435
Java WebSocket API..................................................................................................436
Creating a WebSocket ServerEndPoint......................................................................437
Table of Contents ix
An Echo Server..........................................................................................................438
Sending Messages to All Users..................................................................................440
Using User Properties................................................................................................443
Using Configurators...................................................................................................446
Tracking Session Expiration in the Browser..............................................................447
Summary....................................................................................................................450
Chapter 22: Dynamic Registration and Servlet Container Initializers.....................451
Dynamic Registration................................................................................................451
Servlet Container Initializers......................................................................................454
Summary....................................................................................................................456
Chapter 23: Introduction to Spring MVC...................................................................457
Downloading Spring Framework...............................................................................457
Benefits of Spring MVC............................................................................................457
Spring MVC DispatcherServlet.................................................................................458
The Controller Interface.............................................................................................459
Your First Spring MVC Application..........................................................................460
The View Resolver....................................................................................................467
Annotation-based Controllers....................................................................................467
Writing Request-Handling Methods..........................................................................471
Using An Annotation-Based Controller.....................................................................473
Summary....................................................................................................................478
Chapter 24: Introduction to Struts 2...........................................................................479
The Benefits of Struts 2.............................................................................................479
How Struts 2 Works...................................................................................................480
Interceptors................................................................................................................482
Configuration Files....................................................................................................484
A Simple Struts 2 Application...................................................................................492
Summary....................................................................................................................496
Appendix A: HTML......................................................................................................497
Getting Started...........................................................................................................498
Working with Text.....................................................................................................503
Links..........................................................................................................................513
Images........................................................................................................................516
Lists...........................................................................................................................521
Tables.........................................................................................................................526
Forms.........................................................................................................................531
Multimedia.................................................................................................................552
Appendix B: Cascading Style Sheets...........................................................................559
Overview....................................................................................................................559
Applying Styles..........................................................................................................560
Web Colors................................................................................................................563
Selectors.....................................................................................................................571
Styling Text...............................................................................................................575
Styling Boxes.............................................................................................................576
Styling Links..............................................................................................................578
x Servlet & JSP: A Tutorial, Second Edition
Styling Lists...............................................................................................................579
Styling Tables............................................................................................................581
Styling Forms.............................................................................................................583
Appendix C: Tomcat.....................................................................................................587
Downloading and Configuring Tomcat......................................................................587
Starting and Stopping Tomcat....................................................................................588
Defining A Context....................................................................................................588
Defining A Resource..................................................................................................589
Installing TLS Certificates.........................................................................................589
Appendix D: Web Annotations....................................................................................591
HandlesTypes.............................................................................................................591
HttpConstraint............................................................................................................591
HttpMethodConstraint...............................................................................................592
MultipartConfig.........................................................................................................592
ServletSecurity...........................................................................................................593
WebFilter...................................................................................................................593
WebInitParam............................................................................................................594
WebListener...............................................................................................................594
WebServlet................................................................................................................594
Appendix E: TLS Certificates......................................................................................597
Certificate Overview..................................................................................................597
The KeyTool Program...............................................................................................598
Appendix F: The Spring Framework..........................................................................601
Dependency Injection................................................................................................601
XML-Based Spring Configuration.............................................................................603
Using the Spring IoC Container.................................................................................604
Index..............................................................................................................................611
Introduction
Welcome to Servlet and JSP: A Tutorial, Second Edition. This book covers Servlet 3.1
and JSP 2.3.
Java Servlet technology, or Servlet for short, is the underlying technology for
developing web applications in Java. Sun Microsystems released it in 1996 to compete
with the Common Gateway Interface (CGI), the then standard for generating dynamic
content on the web. The main problem with the CGI was the fact that it spawned a new
process for every HTTP request. This made it difficult to write scalable CGI programs
because creating a process took a lot of CPU cycles. A servlet, on the other hand, is much
faster than a CGI program because a servlet stays in memory after serving its first request,
waiting for subsequent requests.
Today, Servlet is a mature technology that has gone through nine updates (See Table
I.1). Servlet 3.1, the current version, is defined in Java Specification Request (JSR) 340
(http://jcp.org/en/jsr/detail?id=340). It requires Java Standard Edition 7 or later.
Version Release Date Description
Servlet 1.0 June 1997 The specification was released after the emergence
of the first servlet container, Java Web Server.
Servlet 2.0 Released with JDK 1.1
Servlet 2.1 November 1998
Servlet 2.2 August 1999 Part of J2EE 1.2
Servlet 2.3 August 2001JSR 53,
part of J2EE 1.3
Servlet 2.4 November 2003 Part of J2EE 1.4
Servlet 2.5 September 2005 JSR 154, part of Java EE 5
Servlet 3.0 December 2009 JSR 315, part of Java EE 6
Servlet 3.1 May 2013 JSR 340, part of Java EE 7
Servlet 4.0 Planned for Q3 2016 JSR 369, part of Java EE 8
Table I.1: Servlet versions
Not long after the emergence of this technology, Sun released JavaServer Pages (JSP) to
complement Servlet. JSP 1.0 was released in 1999 followed by version 1.1 in the same
year. Table I.2 shows the advancement of JSP. JSP 2.3, the latest version of JSP, is
specified in JSR 245 (http://jcp.org/en/jsr/detail?id=245).
2 Servlet & JSP: A Tutorial, Second Edition
Version Release Date Description
JSP 1.0 1999
JSP 1.1 1999
JSP 1.2 September 2001 JSR 53, the same JSR as Servlet 2.3.
JSP 2.0 November 2003 JSR 152
JSP 2.1 May 2006 JSR 245, part of Java EE 5
JSP 2.2 December 2009 JSR 245. No new JSR since version 2.2 is a
maintenance release for JSP 2.1, part of Java EE 6
JSP 2.3 June 2013 JSR 245. No new JSR since version 2.3 is a second
maintenance release for JSP 2.1, part of Java EE 7
Table I.1: JSP versions
One of the reasons Sun felt the need for JSP was because it was hard to output HTML
from a servlet, as you will learn in the first three chapters of this book. However, people
soon realized it was a bad idea to mix Java code and HTML in a JSP page because doing
so easily yields spaghetti code, which is source code with a complex and tangled
structure. Besides, if you are used to a great IDE that can compile as you type, you will
likely miss this important feature when writing Java code in a JSP page. So, beating the
purpose of having JSP in the first place, you are now advised not to write Java code in
JSP. JSP 2.0 even went as far as providing a way to disable Java code in JSP. Today, the
recommended way of writing Java web applications is to use the Model 2 architecture.
With this architecture you write code in Java classes and use JSP pages to write HTML
and display values from Java objects. You will learn more about Model 2 in Chapter 11,
“Application Design.”
To make it easier to write Servlet/JSP applications, there are now a number of Java-
based web frameworks, the most popular of which include Struts 2, Spring MVC and
JavaServer Faces. These frameworks implement the Model 2 architecture and let you
focus on the business logic and spend less time writing boilerplate code. However, even if
you are using a great framework, without excellent knowledge of Servlet and JSP, you
won’t be able to code effectively and efficiently, hence the need for this book.
The rest of this introduction discusses servlet/JSP application architecture, the HTTP
protocol, and the content of each chapter in this book.
Servlet/JSP Application Architecture
A servlet is a Java program. A JSP page is also a servlet. At runtime a JSP page is
translated and compiled into a servlet.
A servlet application runs inside a servlet container and cannot run on its own. A
servlet container passes requests from the user to the servlet application and responses
from the servlet application back to the user. Most servlet applications include at least
several JSP pages. As such, it’s more appropriate to use the term “servlet/JSP application”
to refer to a Java web application than to leave JSP out.
Web users use web browsers such as Internet Explorer, Mozilla Firefox, or Google
Chrome to access servlet applications. A web browser is referred to as a web client.
Figure I.1 shows the architecture of a servlet/JSP application.
Introduction 3
Figure I.1: Servlet/JSP application architecture
The web server and the web client communicate in a language they both are fluent in: the
Hypertext Transfer Protocol (HTTP). Because of this, a web server is also called an HTTP
server. HTTP is covered in more detail in the next section.
A servlet/JSP container is a special web server that can process servlets as well as
serve static contents. In the past, people were more comfortable running a servlet/JSP
container as a module of an HTTP server such as the Apache HTTP Server because an
HTTP server was considered more robust than a servlet/JSP container. In this scenario the
servlet/JSP container would be tasked with generating dynamic contents and the HTTP
server with serving static resources. Today servlet/JSP containers are considered mature
and widely deployed without an HTTP server. Apache Tomcat and Jetty are the most
popular servlet/JSP containers and are free and open-source. You can download them
from http://tomcat.apache.org and http://www.eclipse.org/jetty, respectively.
Servlet and JSP are two of a multitude of technologies defined in the Java Enterprise
Edition (EE). Other Java EE technologies include Java Message Service (JMS), Enterprise
JavaBeans (EJB), JavaServer Faces (JSF), and Java Persistence. The complete list of
technologies in the Java EE version 7 (the current version) can be found here.
http://www.oracle.com/technetwork/java/javaee/tech/index.html
To run a Java EE application, you need a Java EE container, such as GlassFish, Apache
TomEE, WildFly (formerly known as JBoss), Oracle WebLogic, and IBM WebSphere.
You can deploy a servlet/JSP application in a Java EE container, but a servlet/JSP
container is sufficient and is more lightweight than a Java EE container. Tomcat and Jetty
are not Java EE containers, so they cannot run EJB or JMS.
The Hypertext Transfer Protocol (HTTP)
The HTTP protocol enables web servers and browsers to exchange data over the Internet
or an intranet. The World Wide Web Consortium (W3C), an international community that
develops standards, is responsible for revising and maintaining this protocol. The first
version of HTTP was HTTP 0.9, which was then replaced by HTTP 1.0. Superseding
HTTP 1.0 is HTTP 1.1, the current version. HTTP 1.1 is defined in the W3C’s Request
for Comments (RFC) 2616, which can be downloaded from
http://www.w3.org/Protocols/HTTP/1.1/rfc2616.pdf.
HTTP 1.1 was first released in 1997 and updated in 1999. By Internet standard, not
only is it old. It is ancient! HTTP/2, its replacement, was released in May 2015. At the
4 Servlet & JSP: A Tutorial, Second Edition
time of writing, however, version 1.1 is still the most commonly used HTTP protocol on
this planet.
A web server runs 24x7 waiting for HTTP clients (normally web browsers) to connect
to it and ask for resources. Until HTTP 1.1, it is always the client that initiates a
connection, a server is never in a position to contact a client. To locate a resource, an
Internet user clicks a link that contains a Uniform Resource Locator (URL) or enter one in
the Location box of his/her browser. Here are two examples of URLs:
http://google.com/index.html
http://facebook.com/index.html
The first part of the URLs is http, which identifies the protocol. Not all URLs use HTTP.
For instance, these two URLs are valid even though they are not HTTP-based URLs:
mailto:[email protected]
ftp://[email protected]
In general a URL has this format:
protocol://[host.]domain[:port][/context][/resource][?query string]
or
protocol://IP address[:port][/context][/resource][?query string]
The parts in square brackets are optional, therefore a URL can be as simple as
http://yahoo.ca or http://192.168.1.9. An Internet Protocol (IP) address, by the way, is a
numerical label assigned to a computer or another device. A computer may host more than
one domain, so multiple domains can have the same IP address. In other words, instead of
typing http://google.com, you can use its IP address: http://173.194.123.110. To find out
the IP address of a domain, use the ping program on your computer console:
ping google.com
IP addresses are hard to remember, so people prefer domain names. And, did you know
that you can’t buy example.com and example.org because they are reserved for
documentation purpose?
The host part may be present and identify a totally different location on the Internet or
an intranet. For instance, http://yahoo.com (no host) brings you to a different location than
http://mail.yahoo.com (with a host). Over the years, www has been the most popular host
name and become the default. Normally, http://www.domainName is mapped to
http://domainName.
80 is the default port of HTTP. Therefore, if a web server runs on port 80, you don’t
need the port number to reach the server. Sometimes, however, a web server doesn’t run
on port 80 and you need to type the port number. For example, Tomcat by default runs on
port 8080, so you need to supply the port number:
http://localhost:8080
localhost is a reserved name typically used to refer to the local computer, i.e. the same
computer the web browser is running on.
The context part in a URL refers to the application name, but this is also optional. A
Introduction 5
web server can run multiple contexts (applications) and one of them can be configured to
be the default context. To request a resource in the default context, you skip the context
part in a URL.
Finally, a context can have one or more default resources (ordinarily index.html or
index.htm or default.htm). A URL without a resource name is considered to identify a
default resource. Of course, if more than one default resource exists in a context, the one
with the highest priority will always be returned when a client does not specify a resource
name.
After a resource name comes one or more query string. A query string is a key/value
pair that can be passed to the server to be processed. You’ll learn more about query strings
in the next chapters.
The following subsections discuss HTTP requests and responses in more detail.
HTTP Requests
An HTTP request consists of three components:
▪ Method—Uniform Resource Identifier (URI)—Protocol/Version
▪ Request headers
▪ Entity body
Here is a sample HTTP request:
POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-us
Connection: Keep-Alive
Host: localhost
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/43.0.2357.130 Safari/537.36
Content-Length: 30
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
lastName=Blanks&firstName=Mike
The method—URI—protocol version appears as the first line of the request.
POST /examples/default.jsp HTTP/1.1
Here POST is the request method, /examples/default.jsp the URI, and HTTP/1.1 the
Protocol/Version section.
An HTTP request can use one of the many request methods specified in the HTTP
standards. HTTP 1.1 supports seven request types: GET, POST, HEAD, OPTIONS, PUT,
DELETE, and TRACE. GET and POST are the most commonly used in Internet
applications.
The URI specifies an Internet resource. It is usually interpreted as being relative to the
server’s root directory. Thus, it should always begin with a forward slash /. A Uniform
Resource Locator (URL) is actually a type of URI (See
http://www.ietf.org/rfc/rfc2396.txt).
6 Servlet & JSP: A Tutorial, Second Edition
In an HTTP request, the request header contains useful information about the client
environment and the entity body of the request. For instance, it may contain the language
the browser is set for, the length of the entity body, and so on. Each header is separated by
a carriage return/linefeed (CRLF) sequence.
Between the headers and the entity body is a blank line (CRLF) that is important to
the HTTP request format. The CRLF tells the HTTP server where the entity body begins.
In some Internet programming books, this CRLF is considered the fourth component of an
HTTP request.
In the previous HTTP request, the entity body is simply the following line:
lastName=Blanks&firstName=Mike
The entity body can easily be much longer in a typical HTTP request.
HTTP Responses
Similar to an HTTP request, an HTTP response also consists of three parts:
▪ Protocol—Status code—Description
▪ Response headers
▪ Entity body
The following is an example of an HTTP response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Thu, 3 Sep 2015 13:13:33 GMT
Content-Type: text/html
Last-Modified: Wed, 2 Sep 2015 13:13:12 GMT
Content-Length: 112
<html>
<head>
<title>HTTP Response Example</title>
</head>
<body>
Welcome to Brainy Software
</body>
</html>
The first line of the response header is similar to the first line of the request header. It tells
you that the protocol used is HTTP version 1.1, and that the request succeeded (200 is the
success code).
The response headers contain useful information similar to the headers in an HTTP
request. The entity body of the response is the HTML content of the response itself. The
headers and the entity body are separated by a sequence of CRLFs.
Status code 200 is only issued if the web server was able to find the resource
requested. If a resource cannot be found or cannot be understood, the server sends a
different request code. For instance, 401 is the status code for an unauthorized access and
405 indicates that the HTTP method is not allowed. For a complete list of HTTP status
codes, refer to this online document.
Introduction 7
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
About This Book
This section presents an overview of each chapter.
Chapter 1, “Getting Started” teaches you how to download and install NetBeans, a
free IDE that will help you develop servlet/JSP applications rapidly. It also invites you to
build your first servlet application and test it in a web browser.
Chapter 2, “The Servlet API” introduces the Servlet API and presents several simple
servlets. This chapter focuses on two of the four Java packages in the Servlet API, the
javax.servlet and javax.servlet.http packages.
Chapter 3, “Session Management” discusses session tracking or session management,
a very important topic in web application development due to the statelessness of HTTP.
This chapter explores four techniques for retaining states: URL rewriting, hidden fields,
cookies, and the HTTPSession objects.
JavaServer Pages (JSP) is a technology that complements Servlet. Chapter 4,
“JavaServer Pages” covers the JSP syntax, including its directives, scripting elements, and
actions.
Chapter 5, “The Expression Language” explains one of the most important features
added in JSP 2.0, the Expression Language (EL). The EL aims to make it possible to
author script-free JSP pages and can help you write shorter and more effective JSP pages.
In this chapter you will learn to use the EL to access JavaBeans and scoped objects.
Chapter 6, “JSTL” explains the most important libraries in the JavaServer Pages
Standard Tag Library (JSTL), a collection of custom tag libraries for solving common
problems such as iterating over a map or collection, conditional testing, XML processing,
and even database access and data manipulation.
Most of the time you will use JSTL to access scoped objects and perform other tasks
in your JSP pages. However, for more specific tasks, you may need to write your own
custom tags. Chapter 7, “Writing Custom Tags” teaches you how to do that.
Chapter 8, “Tag Files” discusses tag files, a new feature in JSP 2.0 that makes writing
custom actions simpler. This chapter covers several aspects of writing custom tags using
tag files only.
Chapter 9, “Listeners” talks about event-driven programming in Servlet. It discusses
the event classes and listener interfaces that come with the Servlet API and shows how to
write listeners and use them in servlet/JSP applications.
Chapter 10, “Filters” covers filters, which are web objects that intercept requests.
This chapter discusses the Filter API that includes the Filter, FilterConfig, and
FilterChain interfaces as well as shows how to write filters by implementing the Filter
interface.
Chapter 11, “Application Design” explains the Model 2 Architecture, the
recommended architecture for all but the simplest Java web applications. Several
examples are given to illustrate different components in Model 2 applications.
Chapter 12, “File Upload” shows how to make use of the Servlet 3 file upload feature
and what can be done on the client side to improve user experience.
8 Servlet & JSP: A Tutorial, Second Edition
Chapter 13, “File Download” explains how to send a resource to the browser
programmatically.
Chapter 14, “Accessing the Database” shows how you can use the Java Database
Connectivity (JDBC) to access data stored in a relational database.
Chapter 15, “Java Persistence API” explains an alternative to the JDBC, the Java
Persistence API (JPA). Considered to have a gentle learning curve, the JPA maps Java
objects to a database and offers an easier data persistence mechanism than the JDBC.
Sending and receiving emails programmatically are often a tricky assignment to
beginners. Chapter 16, “Java Mail Programming” talks about the JavaMail technology and
shows how to use it.
The Servlet API comes with classes for wrapping servlet requests and responses. In
Chapter 17, “Decorating Requests and Responses” you learn how to use the Decorator
pattern and these classes to change the behavior of servlet requests and responses.
Chapter 18, “Asynchronous Processing” discusses a new feature in Servlet 3.0 for
processing asynchronous operations. This feature is especially useful when your
servlet/JSP application is a very busy one with one or more long-running operations. This
feature works by assigning those operations to a new thread and thereby releasing the
request processing thread back to the pool, ready to serve another request.
Chapter 19, “Security” explains how to secure a Java web application both
declaratively and programmatically. Four main security topics discussed are
authentication, authorization, confidentiality, and data integrity.
Chapter 20, “Deployment” talks about the deployment process of a servlet/JSP
application and discusses the elements in the deployment descriptor.
Chapter 21, “WebSocket” discusses the Java WebSocket API, whose use in
servlet/JSP applications is made possible in Servlet 3.1. This chapter also presents
examples that use the web browser as the web socket client.
Chapter 22, “Dynamic Registration and Servlet Container Initializers” explains
dynamic registration, a technique for dynamically registering web objects without
application restart.
Chapter 23, “Introduction to Spring MVC” introduces Spring MVC, one of the most
popular Java web frameworks today.
Chapter 24, “Introduction to Struts 2” introduces Struts 2 as an MVC framework. It
explains the basic components and configuration of Struts 2 and presents a simple
application.
Appendix A, “HTML” is a guide to writing HTML5. After all, a web application
sends HTML as its output.
Appendix B, “CSS” is a brief tutorial on using CSS so that you can style your web
pages.
Appendix C, “Tomcat” explains how to install and configure Tomcat and run it in
multiple operating systems.
Appendix D, “Servlet and JSP Annotations” lists all annotations that can be used to
configure a web object, such as a servlet, a listener, or a filter. These annotations were
added in Servlet 3.0 and make the deployment descriptor optional.
Appendix E, “TLS Certificates” explains how you can generate a private/public key
Introduction 9
pair using the KeyTool program and have a trusted authority sign the public key as a
digital certificate.
Appendix F, “Spring Framework” provides a gentle introduction to Spring
Framework.
Downloading the Sample Applications
You can download the zipped sample applications used in this book from this web page.
http://books.brainysoftware.com/download
Choosing a Framework
After you finish this book and master Servlet and JSP, it is a good idea to pick and learn at
least one web framework. There are many excellent frameworks freely available. Struts 2,
JavaServer Faces and Spring MVC are all recommended. A framework solves common
problems in servlet/JSP development and shorten development time.
You may want to check your favorite job sites to find out which frameworks are
currently in high demand.
10 Servlet & JSP: A Tutorial, Second Edition
Chapter 1
Getting Started
The wise developer uses an integrated development environment (IDE), and the web
developer is by no means an exception. An IDE is a tool that allows you to work faster
and more productively. Luckily for Java developers, there are a couple of superior IDEs
that come at no cost. Eclipse EE and NetBeans are some of them. Both are excellent
products but NetBeans is a one-stop shop, unlike Eclipse, which sometimes require you to
install plug-ins. It is not surprising then that many beginners and seasoned programmers
choose NetBeans as their main Java IDE. All examples in this book have also been
developed using NetBeans.
This chapter shows you how to choose the suitable NetBeans bundle, install it and
create your first servlet application. All these in less than fifteen minutes.
Downloading and Installing NetBeans
NetBeans is written in Java and, as such, can run on any platform where Java is available.
Sun Microsystems launched the NetBeans open source project in 2000. The name
NetBeans came from Netbeans Ceska Republika, a Czech company that Sun bought over.
The new project was based on the code Sun acquired as the result of the purchase.
You can download NetBeans free of charge from this website:
http://netbeans.org/downloads
The latest version of NetBeans at the time of writing is 8.0.2, even though version 8.1 is
coming soon. Netbeans ships in five download bundles, and to develop servlet/JSP
applications you need the Java EE bundle.
If you already have a Java SE bundle installed, uninstall it before installing the Java
EE bundle. From experience, installing the Java EE bundle on top of the Java SE bundle
may cause JSP page rendering to not work properly.
Note
NetBeans 8 requires JDK 7 or later. I assume you have JDK 7 or later installed on
your computer. If not, install it before you install NetBeans.
Here are the steps to install the NetBeans Java EE bundle.
1. On Windows, double-click the installer (the .exe file). On Mac OS X, run the
installer (the .dmg file) and on the panel that opens double-click the package icon.
On Linux, run these commands:
$ chmod +x installer-file-name
12 Servlet & JSP: A Tutorial, Second Edition
$ ./installer-file-name
The installation wizard will launch. Figure 1.1 shows the first window of the
installation wizard. It asks you if you want to install GlassFish and Tomcat. By
default, only GlassFish will be installed. However, check the “Apache Tomcat
8.0.15” check box too so you can use Tomcat to run your applications later.
Figure 1.1: Selecting servers to install
2. Click Next. You will see a license agreement, as shown in Figure 1.2.
Chapter 1: Getting Started 13
Figure 1.2: Accepting the NetBeans license agreement
3. Click the “I accept the terms in the license agreement” check box and then click
Next. You will see the License agreement for Junit (See Figure 1.3). It is a good
idea to install JUnit, unless you have space constraint.
14 Servlet & JSP: A Tutorial, Second Edition
Figure 1.3: JUnit license agreement
4. Click Next again. The next window, shown in Figure 1.4, prompts you for an
installation directory. Also, make sure the installer can find the JDK. Most of the
time, Netbeans will be able to find the JDK. If not, browse to the location of the
JDK installed on your local machine.
Chapter 1: Getting Started 15
Figure 1.4: Selecting the installation folder
5. Click Next. The next window asks you to choose an installation folder for
GlassFish.
16 Servlet & JSP: A Tutorial, Second Edition
Figure 1.5: Choosing the installation folder for Glassfish
Most of the time, Netbeans will be able to find the JDK. If not, browse to the
location of the JDK on your local machine.
6. Click Next. In the next window, shown in Figure 1.6, you will be prompted to
select an installation directory for Tomcat.
Chapter 1: Getting Started 17
Figure 1.6: Selecting the installation directory for Tomcat
7. Click Next for the last time. Figure 1.7 shows a window that summarizes what
components will be installed.
18 Servlet & JSP: A Tutorial, Second Edition
Figure 1.7: Confirming installation directories
8. As the last step, click Install. It will take a while, depending on your computer
speed and whether you are installing to an SSD or HDD drive. When it’s finally
done, you’ll see a window similar to that in Figure 1.8.
Chapter 1: Getting Started 19
Figure 1.8: Installation complete
9. Click Finish. Figure 1.9 shows the welcome page.
20 Servlet & JSP: A Tutorial, Second Edition
Figure 1.9: NetBeans’ welcome page
Voilà, you are now ready to create your first servlet application.
Creating A Web Project with NetBeans
Creating a web project with NetBeans involves a couple mouse clicks and entering a
project name and a context path. Follow these steps to create a web project. It assumes
NetBeans is already running.
1. Click the File menu and select New Project. The New Project dialog will open.
This is shown in Figure 1.10.
Chapter 1: Getting Started 21
Figure 1.10: Selecting Project type
2. NetBeans offers many types of applications, including a Java console application,
JavaFX application, Java Web and Java EE application. To create a servlet
application, select Java Web from the Categories window and click Web
Application from the Projects window. Note also that the left window shows the
step you are at. Now it is time to click the Next button. The New Web
Application window, shown in Figure 1.11, opens.
22 Servlet & JSP: A Tutorial, Second Edition
Figure 1.11: The New Web Application window
3. In the New Web Application window you need to enter a project name and select
a project location. The project location is a folder that will contain all your project
resources. Type in getstarted as the project name and browse to a folder in your
local system. After that, click Next. You will see the next wizard of the New Web
Application window.
Chapter 1: Getting Started 23
Figure 1.12: Selecting a server
3. Now, select a server that will be used to run your new application. It is either
Tomcat or GlassFish, both madly loved by Java developers. For this exercise,
though, select Apache Tomcat from the Server dropdown and click Next again.
24 Servlet & JSP: A Tutorial, Second Edition
Figure 1.13: Select a framework
Chapter 1: Getting Started 25
4. The next wizard, shown in Figure 1.13, wants you to select a framework. It is a
good idea to use a web framework such as Spring MVC or JavaServer Faces and I
will show how to do that in the last chapters of this book. For now, though, select
none and click Finish.
That’s it. You just created a web project. You will now see the NetBeans project window
showing a project named getstarted. See Figure 1.14 for details.
Figure 1.14: A web project called getstarted
By default, NetBeans creates a project structure containing several folders and an HTML
page named index.html. NetBeans will also open the HTML file in one of the many
editors it has. You’re very close.
To run the application, right click on the getstarted project icon in the Project pane
and click Run. Netbeans will launch your default browser and direct it to this URL:
http://localhost:8080/getstarted/
This effectively invokes the default resource in your application, which in this case is the
index.html file. Figure 1.15 shows the index.html page in my default browser.
26 Servlet & JSP: A Tutorial, Second Edition
Figure 1.15: The default page of the getstarted application
Note that by default Tomcat and GlassFish run on port 8080. If another application is
already running on this port, Tomcat or GlassFish will fail to launch. If this happens to
you, close the offending application and run the application again.
Troubleshooting
NetBeans is a superb product, but it is not perfect. On Windows, with Netbeans 7 and 8,
Netbeans might fail to start Tomcat. If you encounter this, here is a solution.
1. Go to the bin directory of the Tomcat installation
2. Open the catalina.bat file with Notepad or another text editor.
3. Locate these two lines:
:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"
4. Remove the double quotes surrounding the JAVA_OPTS variable.
5. Locate these two lines:
:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"
6. Again, remove the double quotes surrounding the JAVA_OPTS variable.
7. Save the catalina.bat file.
8. Run the application again from within Netbeans.
Creating A Servlet
When you create a web project with NetBeans, it does not actually creates a servlet,
because it does not know you want one. However, do not be disappointed. It is easy to
create one.
Chapter 1: Getting Started 27
1. Right click on the getstarted project icon and select New > Servlet. You will see
the New Servlet window like the one in Figure 1.16.
Figure 1.16: Entering a class name and package
2. Enter WelcomeServlet as the class name. By convention a servlet class name ends
with Servlet and it is a good idea to follow this convention. In addition, the
package name for the servlet class should not be left blank. In this case, I am using
getstarted.
3. Click Next. The New Servlet window will show a new wizard.
28 Servlet & JSP: A Tutorial, Second Edition
Figure 1.17: Configuring the servlet
4. In the next wizard, you are asked to name the servlet as well as specify a URI to
invoke the servlet. By default the class name will be used as the URI pattern.
However, I do not think you should accept this URI pattern. This URI will
probably be used by users of your application. To the non-technical user, Servlet
means nothing and can be confusing. As such, I changed the URI pattern to
/welcome, as shown in Figure 1.17.
5. Click Finish to complete the process.
As soon as you click the Finish button, NetBeans will create a servlet class according to
what you specified in the New Servlet window. Figure 1.18 shows the servlet code.
Chapter 1: Getting Started 29
Figure 1.18: The created servlet class
For clarity, the servlet class is printed in Listing 1.1.
Listing 1.1: The servlet class
package getstarted;
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;
@WebServlet(name = "WelcomeServlet", urlPatterns = {"/welcome"})
public class WelcomeServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
30 Servlet & JSP: A Tutorial, Second Edition
* @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");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample
code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet WelcomeServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet WelcomeServlet at " +
request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
/**
* Handles the HTTP <code>GET</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 <code>POST</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);
}
Exploring the Variety of Random
Documents with Different Content
Eef “thief’s” my name
I feel no shame;
Eet ees no crime—
Dat rose I got.
Eh! w’at? O! not
Een Juna-time!
—Copyright 1912, by David McKay, and used by kind permission
of author and publisher.
THE SAND STORM
By Lowell Otus Reese
We are thirsty, Pedro mio! and the heat waves leap and beat
Where the Spanish daggers quiver in the mighty desert heat,
And the aching eye looks longing from Old Baldy to the east,
Where the Panamint is crouching like some ugly, hidden beast;
’Tis a hell-wind, Pedro mio! and it beats the sandy hail;
And the Yellow Snake is hissing by the old Mohave trail.
Oh, the loneliness of nature when she turns on you her frown!
When you feel no eye upon you, save the fierce sun glaring down,
Searing death into your body and despair into your soul,
As you reel across the desert with the sky-line for your goal;
When the breath begins to falter and the step begins to fail,
And the Yellow Snake is hissing by the old Mohave trail!
Oh, the awfulness of Nature when she turns on you her frown!
When an unseen hand above you is forever pressing down!
When across the hungry desert flames the scorching sword of
Death,
And the eyes and lips are blackened in the Spirit’s blighting breath!
Oh, the agony of dying, when the step begins to fail,
And the Yellow Snake is hissing by the old Mohave trail!
Oh, the dry and flying sand that stings to fever cheek and brow!
Rain of Hell, O, Pedro mio! and the flame is on us now!
Spiral Phantoms on the desert writhe and wriggle slowly by,
Reaching earthward from the bosom from the black and yellow sky;
Oh, the spiral specters writhing where the yuccas beat and flail,
And the Yellow Snake is hissing by the old Mohave trail!
I have seen it, Pedro mio!—seen it dimly through the wrack!—
Over there beyond the basin where the cloud is whirling black!
Streams of water, peaceful meadows and the shade of bending
trees,
Stirring gently—ah, so gently! in the coolest summer breeze.
Let us turn aside and rest there from the fury of the gale;
For the Yellow Snake is hissing by the old Mohave trail!
Faster—faster, Pedro mio!—for the blood is in my eyes!
I would reach the blessed water ere it o’er my vision dries!
For it thunders in my temples the tumultuous refrain
Of a mountain torrent singing to the first November rain!
Stumble—stumble—onward—farther from the desiccating hail
Where the Yellow Snake is hissing by the old Mohave trail!
We have fallen, Pedro mio! and the vision fair is gone;
But above us and around us yet the tempest hurtles on;
Hark! a swirling raven settles with a flap of twisted wings;
And I seem to feel about us many crawling, creeping things!
We have fallen, Pedro mio! Hark the raging of the gale!
And the Yellow Snake is hissing by the old Mohave trail!
I am dying, Pedro mio! and I fain would go to sleep.
Faugh! the raven ’lights upon me! and the frightened lizards creep
With a rush of tiny claws across my swollen lips! and swift
O’er my breast, a burning blanket, rushing sand-waves eager drift;
We are dying, Pedro mio! in the awful desert gale!
And the Yellow Snake is hissing by the old Mohave trail!
NATHAN HALE
By Francis M. Finch
To drum-beat and heart-beat,
A soldier marches by:
There is color in his cheek,
There is courage in his eye,
Yet to drum-beat and heart-beat
In a moment he must die.
By starlight and moonlight,
He seeks the Briton’s camp;
He hears the rustling flag,
And the arm’d sentry’s tramp;
And the starlight and moonlight
His silent wanderings lamp.
With slow tread and still tread
He scans the tented line;
And he counts the battery guns
By the gaunt and shadowy pine;
And his slow tread and still tread
Gives no warning sign.
The dark wave, the plumed wave,
It meets his eager glance;
And it sparkles ’neath the stars,
Like the glimmer of a lance;—
A dark wave, a plumed wave;
On an emerald expanse.
A sharp clang, a steel clang,
And terror in the sound!
For the sentry, falcon-eyed,
In the camp a spy hath found;
With a sharp clang, a steel clang,
The patriot is bound.
With calm brow, steady brow,
He listens to his doom;
In his look there is no fear,
Nor a shadow-trace of gloom;
But with calm brow and steady brow
He robes him for the tomb.
In the long night, the still night,
He kneels upon the sod;
And the brutal guards withhold
E’en the solemn Word of God!
In the long night, the still night,
He walks where Christ hath trod.
’Neath the blue morn, the sunny morn,
He dies upon the tree;
And he mourns that he can lose
But one life for Liberty;
And in the blue morn, the sunny morn,
His spirit-wings are free.
But his last words, his message-words,
They burn, lest friendly eye
Should read how proud and calm
A patriot could die,
With his last words, his dying words,
A soldier’s battle-cry.
From Fame-leaf and Angel-leaf,
From monument and urn,
The sad of earth, the glad of heaven,
His tragic fate shall learn;
And on Fame-leaf and Angel-leaf
The name of Hale shall burn!
MOTHER AND POET
By Elizabeth Barrett Browning
(Turin, after news from Gaeta, 1861)
Dead! One of them shot in the sea by the east,
And one of them shot in the west by the sea!
Dead! both my boys! when you sit at the feast,
And are wanting a great song for Italy free,
Let none look at me!
Yet I was a poetess only last year,
And good at my art, for a woman, men said;
But this woman, this, who is agonized here,—
The east sea and west sea rhyme on in her head
Forever instead.
What art can a woman be good at? O, vain!
What art is she good at, but hurting her breast
With the milk-teeth of babes, and a smile at the pain?
Ah, boys, how you hurt! you were strong as you pressed,
And I proud, by that test.
What art’s for a woman? to hold on her knees
Both darlings! to feel all their arms round her throat
Cling, strangle a little! to sew by degrees
And ’broider the long-clothes and neat little coat!
To dream and to doat!
To teach them.... It stings there! I made them, indeed,
Speak plain the word country. I taught them, no doubt,
That a country’s a thing men should die for at need.
I prated of liberty, rights, and about
The tyrant cast out.
And when their eyes flashed.... O my beautiful eyes!...
I exulted! nay, let them go forth at the wheels
Of the guns, and denied not.—But then the surprise
When one sits quite alone!—Then one weeps, then one kneels!
God, how the house feels!
At first, happy news came, in gay letters moiled
With my kisses,—of camp-life and glory, and how
They both loved me, and, soon coming home to be spoiled,
In return would fan off every fly from my brow
With their green laurel-bough.
Then was triumph at Turin: “Ancona was free!”
And some one came out of the cheers in the street,
With a face pale as stone, to say something to me,—
My Guido was dead! I fell down at his feet,
While they cheered in the street.
I bore it; friends soothed me; my grief looked sublime
As the ransom of Italy. One boy remained
To be leant on and walked with, recalling the time
When the first grew immortal, while both of us strained
To the height he had gained.
And letters still came, shorter, sadder, more strong,
Writ now but in one hand: “I was not to faint,—
One loved me for two—would be with me ere long:
And ‘Viva l’Italia!’ he died for, our saint,
Who forbids our complaint!”
My Nanni would add, “He was safe, and aware
Of a presence that turned off the balls,—was impressed
It was Guido himself, who knew what I could bear,
And how ’twas impossible, quite dispossessed,
To live on for the rest.”
On which, without pause, up the telegraph-line
Swept smoothly the next news from Gaeta!—Shot.
Tell His Mother. Ah, ah, “his,” “their” mother,—not “mine,”
No voice says “my mother” again to me. What!
You think Guido forgot?
Are souls straight so happy that, dizzy with heaven,
They drop earth’s affections, conceive not of woe?
I think not. Themselves were too lately forgiven
Through that love and sorrow which reconciled so
The above and below.
O Christ of the seven wounds, who look’dst through the dark
To the face of Thy mother! consider, I pray,
How we common mothers stand desolate, mark,
Whose sons, not being Christs, die with eyes turned away,
And no last word to say!
Both boys dead? but that’s out of nature. We all
Have been patriots, yet each house must always keep one.
’Twere imbecile, hewing out roads to a wall;
And, when Italy’s made, for what end is it done,
If we have not a son?
Ah, ah, ah! when Gaeta’s taken, what then?
When the fair wicked queen sits no more at her sport
Of the fire-balls of death crashing souls out of men?
When the guns of Cavalli with final retort
Have cut the game short;
When Venice and Rome keep their new jubilee,
When your flag takes all heaven for its white, green, and red,
When you have your country from mountain to sea,
When King Victor has Italy’s crown on his head
(And I have my dead),—
What then? Do not mock me. Ah, ring your bells low,
And burn your lights faintly! My country is there,
Above the star pricked by the last peak of snow:
My Italy’s THERE,—with my brave civic pair,
To disfranchise despair!
Forgive me. Some women bear children in strength,
And bite back the cry of their pain in self-scorn;
But the birth-pangs of nations will wring us at length
Into wail such as this,—and we sit on forlorn
When the man-child is born.
Dead! One of them shot by the sea in the east,
And one of them shot in the west by the sea!
Both! both my boys! If in keeping the feast,
You want a great song for your Italy free,
Let none look at me!
DORA
With farmer Allan, at the farm, abode William and Dora. William
was his son, and she his niece. He often looked at them and
thought, “I’ll make them man and wife.” Now Dora felt her uncle’s will
in all, and yearned towards William; but the youth, because he had
always been with her in the house, thought not of Dora.
Then there came a day when Allan called his son, and said, “My
son, I married late, but I wish to see my grandchild on my knees
before I die: and I have set my heart upon a match. Now therefore
look to Dora; she is well to look at, thrifty too beyond her age. She is
my brother’s daughter: he and I had once hard words, and parted,
and he died in foreign lands; but for his sake I cared for his daughter
Dora: take her for your wife; for I have wished this marriage, night
and day, for many years.”
But William answered short: “I cannot marry Dora; by my life, I will
not marry Dora.”
Then the old man was wroth, and doubled up his hands, and said:
“You will not, boy! You dare to answer thus? But in my time a father’s
word was law, and so it shall be now for you. Look to it; consider,
William: take a month to think, and let me have an answer to my
wish, or by the Lord that made me, you shall pack, and never more
darken my doors again.”
But William answered madly; bit his lips, and broke away. The
more he looked at her the less he liked her; and his ways were
harsh; but Dora bore them meekly. Then, before the month was out
he left his father’s house, and hired himself to work within the fields;
and, half in love, half spite, he wooed and wed a laborer’s daughter,
Mary Morrison.
When the wedding bells were ringing, Allan called his niece and
said: “My girl, I love you well; but if you speak with him who was my
son, or change a word with her he calls his wife, my home is none of
yours. My will is law.” And Dora promised, being meek. She thought,
“It cannot be: my uncle’s mind will change!” And days went on, and
there was born a boy to William; then distresses came on him, and
day by day he passed his father’s gate, heart-broken, and his father
helped him not. But Dora stored what little she could save, and sent
it them by stealth, nor did they know who sent it; till at last a fever
seized on William, and in harvest time he died. Then Dora went to
Mary. Mary sat and looked with tears upon her boy, and thought hard
things of Dora. Dora came and said: “I have obeyed my uncle until
now, and I have sinned, for it was all through me this evil came on
William at the first. But, Mary, for the sake of him that’s gone, and for
your sake, the woman that he chose, and for this orphan, I am come
to you. You know there has not been for these five years so full a
harvest: let me take the boy, and I will set him in my uncle’s eye
among the wheat; that when his heart is glad of the full harvest, he
may see the boy, and bless him for the sake of him that’s gone.” And
Dora took the child and went her way across the wheat, and sat
upon a mound that was unsown, where many poppies grew. Far off
the farmer came into the field and spied her not; for none of all his
men dare tell him Dora waited with the child. And Dora would have
risen and gone to him, but her heart failed her; and the reapers
reaped, and the sun fell, and all the land was dark.
But when the morrow came, she rose and took the child once
more, and sat upon the mound; and made a little wreath of all the
flowers that grew about, and tied it round his hat to make him
pleasing in her uncle’s eye. Then when the farmer passed into the
field he spied her, and he left his men at work, and came and said:
“Where were you yesterday? Whose child is that? What are you
doing here?”
So Dora cast her eyes upon the ground, and answered softly,
“This is William’s child!”
“And did I not,” said Allan, “did I not forbid you, Dora?”
Dora said again: “Do with me as you will, but take the child, and
bless him for the sake of him that’s gone!”
And Allan said, “I see it is a trick got up betwixt you and the
woman there. I must be taught my duty, and by you! You knew my
word was law, and yet you dared to slight it. Well!—for I will take the
boy; but go you hence, and never see me more.”
So saying he took the boy that cried aloud and struggled hard. The
wreath of flowers fell at Dora’s feet. She bowed over her hands, and
the boy’s cry came to her from the field, more and more distant. She
bowed down her head, remembering the day when first she came,
and all the things that had been. She bowed down and wept in
secret; and the reapers reaped, and the sun fell, and all the land was
dark. Then Dora went to Mary’s house, and stood upon the
threshold. Mary saw the boy was not with Dora. She broke out in
praise to God, that helped her in her widowhood. And Dora said, “My
uncle took the boy; but, Mary, let me live and work with you; he says
that he will never see me more.”
Then answered Mary, “This shall never be, that thou shouldst take
my trouble on thyself: and, now I think, he shall not have the boy, for
he will teach him hardness, and to slight his mother; therefore thou
and I will go, and I will have my boy, and bring him home; and I will
beg of him to take thee back: but if he will not take thee back again,
then thou and I will live within one house, and work for William’s
child, until he grows of age to help us.”
So the women kissed each other, and set out, and reached the
farm. The door was off the latch: they peeped and saw the boy set
up betwixt his grandsire’s knees, who thrust him in the hollows of his
arms, and clapt him on the hands and on the cheeks, like one that
loved him: and the lad stretched out and babbled for the golden seal
that hung from Allan’s watch, and sparkled by the fire. Then they
came in: but when the boy beheld his mother, he cried out to come
to her: and Allan set him down, and Mary said: “O Father!—if you let
me call you so—I never came a-begging for myself, or William, or
this child; but now I come for Dora: take her back, she loves you
well. O Sir, when William died, he died at peace with all men; for I
asked him, and he said he could not ever rue his marrying me—I
had been a patient wife: but, Sir, he said that he was wrong to cross
his father thus: ‘God bless him!’ he said, ‘and may he never know the
troubles I have gone through!’ Then he turned his face and passed—
unhappy that I am! But now, Sir, let me have my boy, for you will
make him hard, and he will learn to slight his father’s memory; and
take Dora back, and let all be as it was before.”
So Mary said, and Dora hid her face by Mary. There was silence in
the room; and all at once the old man burst in sobs: “I have been to
blame—to blame. I have killed my son. I have killed him—but I loved
him—my dear son. May God forgive me! I have been to blame. Kiss
me, my children.”
Then they clung about the old man’s neck, and they kissed him
many times. And Allan was broken with remorse; and all his love
came back a hundred-fold; and for three hours he sobbed o’er
William’s child thinking of William. So those four abode in one house
together; and as years went forward, Mary took another mate; but
Dora lived unmarried until her death.
THE FAMINE[13]
By Henry Wadsworth Longfellow
O the long and dreary Winter!
O the cold and cruel Winter!
Ever thicker, thicker, thicker,
Froze the ice on lake and river,
Ever deeper, deeper, deeper
Fell the snow o’er all the landscape,
Fell the covering snow, and drifted
Through the forest, round the village.
Hardly from his buried wigwam
Could the hunter force a passage;
With his mittens and his snow-shoes
Vainly walked he through the forest,
Sought for bird or beast and found none,
Saw no track of deer or rabbit,
In the snow beheld no footprints,
In the ghastly, gleaming forest
Fell, and could not rise from weakness,
Perished there from cold and hunger.
O the famine and the fever!
O the wasting of the famine!
O the blasting of the fever!
O the wailing of the children!
O the anguish of the women!
All the earth was sick and famished;
Hungry was the air around them,
Hungry was the sky above them,
And the hungry stars in heaven
Like the eyes of wolves glared at them!
Into Hiawatha’s wigwam
Came two other guests, as silent
As the ghosts were, and as gloomy;
Waited not to be invited,
Did not parley at the doorway,
Sat there without word of welcome
In the seat of Laughing Water;
Looked with haggard eyes and hollow
At the face of Laughing Water.
And the foremost said: “Behold me!
I am Famine, Bukadawin!”
And the other said: “Behold me!
I am Fever, Ahkosewin!”
And the lovely Minnehaha
Shuddered as they looked upon her,
Shuddered at the words they uttered,
Lay down on her bed in silence,
Hid her face, but made no answer;
Lay there trembling, freezing, burning
At the looks they cast upon her,
At the fearful words they uttered.
Forth into the empty forest
Rushed the maddened Hiawatha;
In his heart was deadly sorrow,
In his face a stony firmness;
On his brow the sweat of anguish
Started, but it froze and fell not.
Wrapped in furs and armed for hunting,
With his mighty bow of ash-tree,
With his quiver full of arrows,
With his mittens, Minjekahwun,
Into the vast and vacant forest
On his snow-shoes strode he forward.
“Gitche Manito, the Mighty!”
Cried he with his face uplifted
In that bitter hour of anguish,
“Give your children food, O Father!
Give us food, or we must perish!
Give me food for Minnehaha,
For my dying Minnehaha!”
Through the far-resounding forest,
Through the forest vast and vacant
Rang that cry of desolation,
But there came no other answer
Than the echo of his crying,
Than the echo of the woodlands,
“Minnehaha! Minnehaha!”
All day long roved Hiawatha
In that melancholy forest,
Through the shadow of whose thickets,
In the pleasant days of Summer,
Of that ne’er forgotten Summer,
He had brought his young wife homeward
From the land of the Dacotahs;
When the birds sang in the thickets,
And the streamlets laughed and glistened,
And the air was full of fragrance,
And the lovely Laughing Water
Said with voice that did not tremble,
“I will follow you, my husband!”
In the wigwam with Nokomis,
With those gloomy guests, that watched her,
With the Famine and the Fever,
She was lying, the Beloved,
She, the dying Minnehaha.
“Hark!” she said; “I hear a rushing,
Hear a roaring and a rushing,
Hear the Falls of Minnehaha
Calling to me from a distance!”
“No, my child!” said old Nokomis,
“’Tis the night-wind in the pine-trees!”
“Look!” she said; “I see my father
Standing lonely at his doorway,
Beckoning to me from his wigwam
In the land of the Dacotahs!”
“No, my child!” said old Nokomis,
“’Tis the smoke that waves and beckons!”
“Ah!” said she, “the eyes of Pauguk
Glare upon me in the darkness,
I can feel his icy fingers
Clasping mine amid the darkness!
Hiawatha! Hiawatha!”
And the desolate Hiawatha,
Far away amid the forest,
Miles away among the mountains,
Heard that sudden cry of anguish,
Heard the voice of Minnehaha
Calling to him in the darkness,
“Hiawatha! Hiawatha!”
Over snow-fields waste and pathless,
Under snow-encumbered branches,
Homeward hurried Hiawatha,
Empty-handed, heavy-hearted,
Heard Nokomis moaning, wailing:
“Wahonowin! Wahonowin!
Would that I had perished for you,
Would that I were dead as you are!
Wahonowin! Wahonowin!”
And he rushed into the wigwam,
Saw the old Nokomis slowly
Rocking to and fro and moaning,
Saw his lovely Minnehaha
Lying dead and cold before him,
And his bursting heart within him
Uttered such a cry of anguish,
That the forest moaned and shuddered,
That the very stars in heaven
Shook and trembled with his anguish.
Then he sat down, still and speechless,
On the bed of Minnehaha,
At the feet of Laughing Water,
At those willing feet, that never
More would lightly run to meet him,
Never more would lightly follow.
With both hands his face he covered,
Seven long days and nights he sat there,
As if in a swoon he sat there,
Speechless, motionless, unconscious
Of the daylight or the darkness.
Then they buried Minnehaha;
In the snow a grave they made her,
In the forest deep and darksome,
Underneath the moaning hemlocks;
Clothed her in her richest garments,
Wrapped her in her robes of ermine;
Covered her with snow, like ermine;
Thus they buried Minnehaha.
And at night a fire was lighted,
On her grave four times was kindled,
For her soul upon its journey
To the Islands of the Blessed.
From his doorway Hiawatha
Saw it burning in the forest,
Lighting up the gloomy hemlocks;
From his sleepless bed uprising,
From the bed of Minnehaha,
Stood and watched it at the doorway,
That it might not be extinguished,
Might not leave her in the darkness.
“Farewell,” said he, “Minnehaha!
Farewell, O my Laughing Water!
All my heart is buried with you,
All my thoughts go onward with you!
Come not back again to labor,
Come not back again to suffer,
Where the Famine and the Fever
Wear the heart and waste the body.
Soon my task will be completed,
Soon your footsteps I shall follow
To the Islands of the Blessed,
To the Kingdom of Ponemah,
To the Land of the Hereafter!”
THE CHILDREN OF THE BATTLE-FIELD
By James Gowdy Clark
Upon the field of Gettysburg
The summer sun was high,
When Freedom met her haughty foe
Beneath a northern sky.
Among the heroes of the North
That swelled her grand array,
And rushed like mountain eagles forth
From happy homes away,
There stood a man of humble fame,—
A sire of children three,—
And gazed within a little frame
His pictured ones to see:
And blame him not if, in the strife,
He breathed a soldier’s prayer,—
“O Father! shield the soldier’s wife,
And for his children care.”
Upon the field of Gettysburg,
When morning shone again,
The crimson cloud of battle burst
In streams of fiery rain:
Our legions quelled the awful flood
Of shot and steel and shell,
While banners, marked with ball and blood,
Around them rose and fell:
And none more nobly won the name
Of Champion of the Free
Than he who pressed the little frame
That held his children three;
And none were braver in the strife
Than he who breathed the prayer,—
“O Father! shield the soldier’s wife,
And for his children care.”
Upon the field of Gettysburg
The full moon slowly rose,—
She looked, and saw ten thousand brows
All pale in death’s repose;
And down beside a silver stream,
From other forms away,
Calm as a warrior in a dream,
Our fallen comrade lay;
His limbs were cold, his sightless eyes
Were fixed upon the three
Sweet stars that rose in memory’s skies
To light him o’er death’s sea.
Then honored be the soldier’s life,
And hallowed be his prayer,—
“O Father! shield the soldier’s wife,
And for his children care.”
PRESIDENT LINCOLN’S FUNERAL
By Sarah E. Carmichael
Toll! Toll!
Toll! Toll!
All rivers seaward wend.
Toll! Toll!
Toll! Toll!
Weep for the nation’s friend.
Every home and hall was shrouded,
Every thoroughfare was still;
Every brow was darkly clouded,
Every heart was faint and chill.
Oh! the inky drop of poison
In our bitter draught of grief!
Oh! the sorrow of a nation
Mourning for its murdered chief!
Toll! Toll!
Toll! Toll!
Bound in the reaper’s sheaf—
Toll! Toll!
Toll! Toll!
All mortal life is brief.
Toll! Toll!
Toll! Toll!
Weep for the nation’s chief!
Bands of mourning draped the homestead,
And the sacred house of prayer;
Mourning folds lay black and heavy
On true bosoms everywhere:
Yet there were no tear-drops streaming
From the deep and solemn eye
Of the hour that mutely waited
Till the funeral train went by.
Oh! there is a woe that crushes
All expression with its weight!
There is pain that numbs and hushes
Feeling’s sense, it is so great.
Strongest arms were closely folded,
Most impassioned lips at rest;
Scarcely seemed a heaving motion
In the nation’s wounded breast;
Tears were frozen in their sources,
Blushes burned themselves away;
Language bled through broken heart-threads,
Lips had nothing left to say.
Yet there was a marble sorrow
In each still face, chiseled deep;
Something more than words could utter,
Something more than tears could weep.
Selfishly the nation mourned him,
Mourned its chieftain and its friend;
Eye no traitor mist could darken,
Arm no traitor power could bend;
Heart that gathered the true pulses
Of the land’s indignant veins,
And, with their tempestuous spurning,
Broke the slave’s tear-rusted chains:
Heart that tied its iron fibers
Round the Union’s starry band;
Martyr’s heart, that upward beating,
Broke on hate’s assassin hand!
Oh! the land he loved will miss him,
Miss him in its hour of need!
Mourns the nation for the nation
Till its tear-drops inward bleed.
There is one whose life will mourn him,
With a deep, unselfish woe;
One who owned him chief and master
Ere the nation named him so.
That the land he loved will miss him
Does she either think or care?
No! the chieftain’s heart is shrouded,
And her woman’s world was there.
No! the nation was her rival;
Let its glory shine or dim,
He hath perished on its altar—
What were many such to him?
Toll! Toll!
Toll! Toll!
Never again—no more—
Comes back to earth the life that goes
Hence to the Eden shore!
Let him rest!—it is not often
That his soul hath known repose;
Let him rest!—they rest but seldom
Whose successes challenge foes.
He was weary—worn with watching;
His life-crown of power hath pressed
Oft on temples sadly aching—
He was weary, let him rest.
Toll, bells at the Capital!
Bells of the land, toll!
Sob out your grief with brazen lungs—
Toll! Toll! Toll!
THE FISHERMAN’S STORY
By Herbert Bashford
I knew he was morose that day
Because he did not speak to me,
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!
ebookfinal.com