100% found this document useful (5 votes)
146 views

Ebooks File Murach S Java Servlets and JSP 3rd Edition Edition Joel Murach All Chapters

ebook

Uploaded by

qmmsabdy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
146 views

Ebooks File Murach S Java Servlets and JSP 3rd Edition Edition Joel Murach All Chapters

ebook

Uploaded by

qmmsabdy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Full download ebook at ebookgate.

com

Murach s Java Servlets and JSP 3rd Edition


Edition Joel Murach

https://ebookgate.com/product/murach-s-java-
servlets-and-jsp-3rd-edition-edition-joel-murach/

Download more ebook from https://ebookgate.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Murach s Java SE 6 1st Ed. Edition Joel Murach

https://ebookgate.com/product/murach-s-java-se-6-1st-ed-edition-
joel-murach/

Murach s C 2010 4th Edition Joel Murach

https://ebookgate.com/product/murach-s-c-2010-4th-edition-joel-
murach/

Murach s HTML5 and CSS3 3rd Edition Anne Boehm

https://ebookgate.com/product/murach-s-html5-and-css3-3rd-
edition-anne-boehm/

Murach s JavaScript 2nd Edition Mary Delamater

https://ebookgate.com/product/murach-s-javascript-2nd-edition-
mary-delamater/
Murach s HTML5 and CSS3 1st Edition Zak Ruvalcaba

https://ebookgate.com/product/murach-s-html5-and-css3-1st-
edition-zak-ruvalcaba/

Murach s SQL Server 2012 for Developers 1st Edition


Bryan Syverson

https://ebookgate.com/product/murach-s-sql-server-2012-for-
developers-1st-edition-bryan-syverson/

Developing Java Servlets 2nd Edition James Goodwill

https://ebookgate.com/product/developing-java-servlets-2nd-
edition-james-goodwill/

Murach s ADO NET 4 Database Programming with VB 2010


4th Edition Anne Boehm

https://ebookgate.com/product/murach-s-ado-net-4-database-
programming-with-vb-2010-4th-edition-anne-boehm/

Murach s ASP NET 4 Web Programming with VB 2010 4th


Edition Anne Boehm

https://ebookgate.com/product/murach-s-asp-net-4-web-programming-
with-vb-2010-4th-edition-anne-boehm/
I

3RD EDITION
TRAINING & REFERENCE

3RD EDITION

Joel Murach
Michael Urban

MIKE MURACH & ASSOCIATES, INC.


4340 N. Knoll Ave. • Fresno, CA 93722
www.murach.com • [email protected]
Authors: Joel Murach
Michael Urban
Editor: Ray Halliday
Production: Maria Spera

Books for Java programmers


Murach's Java Programming
Murach's Android Programming
Murach's Java Servlets and ISP (Jrd Edition)

Books for web developers


Murach's HTML5 and CSS3
Murach's Dreamweaver CC
Murach's JavaScript andjQuery
Murach's JavaScript and DOM Scripting
Murach's PHP and MySQL

Books for .NET programmers


Murach's C# 2012
Murach's ASP.NET 4.5 Web Programming with C# 2012
Murach's Visual Basic 2012
Murach's ASP.NET 4.5 Web Programming with VB 2012

Books for database developers


Murach's MySQL
Murach's Oracle SQL and PL!SQL
Murach's SQL Server 2012 for Developers

Books for IBM mainframe programmers


Murach's OS/390 and z/OS JCL
Murach's Mainframe COBOL
Murach's CfCS for the COBOL Programmer

Please check www.murach.com


for the most up-to-date Murach books

© 2014, Mike Murach & Associates, Inc.


All rights reserved.
Printed in the United States of America

10 9 8 7 6 5 4 3 2 1
ISBN-13: 978-1-890774-78-3
Content
Introduction

Section 1 Get started right


Chapter 1 An introduction to web programming with Java 3
Chapter 2 How to structure a web application with the MVC pattern 29
Chapter 3 How to use NetBeans and Tomcat 49

Section 2 Essential servlet and JSP skills


Chapter 4 A crash course in HTML5 and CSS3 89
Chapter 5 How to develop serv lets 127
Chapter 6 How to develop JavaServer Pages 173
Chapter 7 How to work with sessions and cookies 201
Chapter 8 How to use EL 243
Chapter 9 How to use JSTL 269
Chapter 10 How to use custom JSP tags 307

Section 3 Essential database skills


Chapter 11 How to use a MySQL database 347
Chapter 12 How to use JDBC to work with a database 377
Chapter 13 How to use JPA to work with a database 421

Section 4 Advanced servlet and JSP skills


Chapter 14 How to use JavaMail to send email 459
Chapter 15 How to use SSL to work with a secure connection 483
Chapter 16 How to restrict access to a web resource 501
Chapter 17 More security skills 525
Chapter 18 How to work with HTTP requests and responses 543
Chapter 19 How to work with listeners 571
Chapter 20 How to work with filters 587
Chapter 21 How to work with JavaServer Faces 613

Section 5 The Music Store website


Chapter 22 An introduction to the Music Store website 643
Chapter 23 The applications of the website 673

Appendixes
Appendix A How to set up your PC for this book 691
Appendix B How to set up your Mac for this book 711
••
Expanded contents VI I

Expanded contents
Section 1 Get started right
Chapter 1 An introduction to web applications
A typical web application ............................................................................................... 4
The components of a web application ............................................................................ 6
How static web pages work .............................................................................................8
How dynamic web pages work ..................................................................................... 10
Three approaches for Java web applications ................................ 12
Servlet/JSP .................................................................................................................... 12
JSF ................................................................................................................................. 12
Spring Framework ........................................................................................................ 12
An introduction to servlet/JSP web development ........................ 14
The software components ............................................................................................. 14
The architecture ............................................................................................................ 16
The standard directories and files ................................................................................. 18
Software for developing Java web applications ............................20
IDEs for developing Java web applications .................................................................. 20
Web servers for Java web applications ......................................................................... 22
Database servers for Java web applications .................................................................. 22
Tools for deploying Java web applications ................................................................... 24

Chapter 2 How to structure a web application


with the MVC patt'ern
Two patterns for servlet/JSP applications ..................................... 30
The Model 1 pattern ...................................................................................................... 30
The Model 2 (MVC) pattern ......................................................................................... 32
A servlet/JSP application that uses the MVC pattern ................... 34
The user interface ......................................................................................................... 34
The HTML for the first page ........................................................................................ 36
The CSS for both web pages ......................................................................................... 38
The servlet for the back-end processing ....................................................................... 40
The web.xml file ........................................................................................................... 42
The User class ............................................................................................................... 44
The JSP for the second page .........................................................................................46

Chapter 3 How to use NetBeans and Tomcat


How to get started with NetBeans .................................................. 50
How to start NetBeans .................................................................................................. 50
How to create a new web application ........................................................................... 52
How to use the Projects window ................................................................................... 56
How to open and close projects .................................................................................... 58
How to build , deploy, and run a web application ......................................................... 60
How to work with HTML and JSP files ............................................ 62
How to add an HTML or JSP' file ................................................................................. 62
How to edit an HTML or JSP file .................................................................................64
•••
VI 11 Expanded contents

How to work with Java files ............................................................. 66


How to add a Java class ................................................................................................. 66
How to add a servlet...................................................................................................... 68
How to edit a Java file ................................................................................................... 70
How to work with XML files .............................................................. 72
How to edit the web.xml file......................................................................................... 72
How to edit other XML files ......................................................................................... 72
Other skills for working with web applications ............................. 74
How to add existing files to a project............................................................................ 74
How to deploy a web application to a remote server .................................................... 74
How to work with a web application server .................................................................. 76
How to add a class library or a JAR file to a project .................................................... 78
How to register a database connection ......................................................................... 80

Section 2 Essential servlet and JSP skills


Chapter 4 A crash course in HTMLS and CSS3
How to work with HTML ................................................................... 90
The starting HTML for a web page.............................................................................. 90
How to code HTML elements ...................................................................................... 92
How to use the HTML5 semantic elements ................................................................. 94
How to use the div and span elements with HTML5 ................................................... 96
How to ensure cross-browser compatibility ................................................................. 98
How to code links ....................................................................................................... 100
How to include images ................................................................................................ 102
How to code tables ...................................................................................................... 104
How to work with CSS .................................................................... 106
How to provideCSS styles for an HTML page .......................................................... 106
How to code the basic CSS selectors .......................................................................... 108
How to codeCSS rule sets and com ments ................................................................. 110
How to useCSS to format a table ............................................................................... 112
How to code HTML forms ............................................................... 114
How to code a form ..................................................................................................... 114
How to code text boxes ............................................................................................... 116
How to code buttons ................................................................................................... 118
How to code check boxes and radio buttons............................................................... 120
How to code combo boxes and list boxes ................................................................... 122

Chapter 5 How to develop servlets


How to create and map a servlet ................................................... 128
How to create a servlet ................................................................................................ 128
How to map a servlet with the web.xml file ............................................................... 130
How to map a servlet with an annotation ................................................................... 132
How to request a servlet ................................................................ 134
How to use the HTTP GET method ........................................................................... 134
How to use the HTTP POST method ......................................................................... 136
When to use the HTTP GET and POST methods ...................................................... 136
Skills for working with servlets ..................................................... 138
How to get the values of the parameters..................................................................... 138
How to get the real path for a file ............................................................................... 140
Expanded contents IX

How to get and set request attributes .......................................................................... 142


How to forward requests ............................................................................................. 144
How to redirect responses........................................................................................... 144
How to validate data ....................................................................... 146
How to validate data on the client .............................................................................. 146
How to validate data on the server ............................................................................. 146
How to work with the web.xml file ................................................. 150
A complete web.xml file ............................................................................................. 150
How to work with initialization parameters ............................................................... 152
How to implement custom error handling .................................................................. 156
More skills for working with servlets ............................................ 160
How the methods of a servlet work ............................................................................ 160
Why you shouldn't use instance variables in servlets ................................................ 162
How to work with servlet errors .................................................... 164
How to solve common servlet problems ..................................................................... 164
How to print debugging data to the console ............................................................... 166
How to print debugging data to a log file ................................................................... 168

Chapter 6 How to develop JavaServer Pages


A crash course in EL and JSTL ..................................................... 174
How to code a JavaBean ............................................................................................. 174
How to use EL to get attributes and JavaBean properties .......................................... 176
How to enable the core JSTL library .......................................................................... 178
How to use the JSTL if tag ......................................................................................... 178
How to use JSP tags ....................................................................... 180
How to code directives, scriptlets, and expressions ................................................... 180
How to code comments in a JSP ................................................................................. 182
How to use standard JSP tags with Java Beans .......................... 184
An introduction to standard JSP tags ......................................................................... 184
How to code the useBean tag ...................................................................................... 186
How to code the getProperty and setProperty tags .................................................... 188
How to include a file in a JSP ........................................................ 190
A JSP that includes a header and footer file ............................................................... 190
Three techniques for including files in a JSP ............................................................. 194
How to fix common JSP errors...................................................... 196
Chapter 7 How to work with sessions and cookies
An introduction to session tracking .............................................202
Why session tracking is difficult with HTTP ............................................................. 202
How session tracking works in Java ...........................................................................202
An application that needs session tracking.................................................................204
How to work with sessions ............................................................206
How to set and get session attributes .......................................................................... 206
More methods of the session object. ........................................................................... 208
How to provide thread-safe access to the session object............................................ 210
How to work with cookies .............................................................. 212
An introduction to cookies ......................................................................................... 212
How to create and use cookies.................................................................................... 214
How to view and delete cookies ................................................................................. 216
X Expanded contents

Four methods for working with cookies ..................................................................... 218


A utility class for working with cookies ..................................................................... 220
How to work with URL rewriting and hidden fields ..................... 222
How to use URL rewriting to pass parameters .......................................................... 222
How to use hidden fields to pass parameters .............................................................. 224
The Download application ............................................................. 226
The user interface ....................................................................................................... 226
The file structure ......................................................................................................... 228
The web.xml file ......................................................................................................... 228
The code for the JSPs .................................................................................................. 230
The code for the servlet .............................................................................................. 234

Chapter 8 How to use EL


An introduction to JSP Expression Language ............................ 244
Advantages of EL........................................................................................................244
Disadvantages of EL ...................................................................................................244
Essential skills for working with EL.............................................. 246
How to use the dot operator to work with JavaBeans and maps ................................246
How to use EL to specify scope ................................................................................. 248
How to use the [ ] operator to work with arrays and lists ........................................... 250
How to use the dot operator to access nested properties ............................................ 252
Other skills for working with EL .................................................... 254
How to use the [ ] operator to access attributes .......................................................... 254
How to work with the other implicit EL objects ........................................................ 256
How to work with other EL operators ........................................................................ 260
How to disable EL....................................................................................................... 264
How to disable scripting ............................................................................................. 264

Chapter 9 How to use JSTL


An introduction to JSTL ................................................................. 270
The JSTL libraries ...................................................................................................... 270
How to make the JSTL JAR files available to your application ................................. 270
How to code the taglib directive ................................................................................. 270
How to code a JSTL tag .............................................................................................. 270
How to view the documentation for a library ............................................................. 272
How to work with the JSTL core library ....................................... 274
How to use the out tag ................................................................................................. 274
How to use the for Each tag ......................................................................................... 276
How to use the forTokens tag ...................................................................................... 278
Four more attributes for looping ................................................................................. 280
How to use the if tag ................................................................................................... 282
How to use the choose tag .......................................................................................... 284
How to use the url tag ................................................................................................. 286
Other tags in the JSTL core library ............................................................................ 288
The Cart application ....................................................................... 290
The user interface ....................................................................................................... 290
The code for the business classes ............................................................................... 292
The code for the servlets and JSPs .............................................................................. 296
Expanded contents XI

Chapter 10 How to use custom JSP tags


How to code a custom tag that doesn't have a body .................. 308
The tag ........................................................................................................................ 308
The tag element ........................................................................................................... 310
The tag class................................................................................................................ 312
How to code a custom tag that has a body .................................. 314
The tag ........................................................................................................................ 314
The tag element ........................................................................................................... 316
The tag class................................................................................................................ 316
How to code a custom tag that has attributes ............................. 318
The tag ........................................................................................................................ 318
The tag element ........................................................................................................... 320
The tag class................................................................................................................ 322
How to code a custom tag that reiterates its body ..................... 324
The tag ........................................................................................................................ 324
The tag element ........................................................................................................... 326
The tag class................................................................................................................ 326
How to work with scripting variables............................................330
An introduction to scripting variables ........................................................................ 330
The TEI class for four scripting variables .................................................................. 332
Classes, methods, and fields for working with custom tags ..... 334
Methods and fields of the Tag Support class ............................................................... 334
Methods and fields of the PageContext class.............................................................. 336
Methods and fields of the BodyTagSupport class ....................................................... 338
Methods and fields of the BodyContent class............................................................. 340

Section 3 Essential database skills


Chapter 11 How to use a MySQL database
An introduction to MySQL .............................................................348
What MySQL provides ............................................................................................... 348
Two ways to interact with MySQL ............................................................................. 350
How to use MySQL Workbench ..................................................... 352
The Home tab of MySQL Workbench ........................................................................ 352
How to open a database connection............................................................................ 354
How to start and stop the MySQL ser ver ................................................................... 356
How to enter and execute a SQL statement ................................................................ 358
How to enter and execute a SQL script....................................................................... 360
The SQL statements for creating a database ..............................362
How to create, select, and drop a database ................................................................. 362
How to create and drop a table ................................................................................... 364
How to insert multiple rows into a table ..................................................................... 366
The SQL statements for data manipulation ................................. 368
How to select data from a single table ........................................................................ 368
How to select data from multiple tables ..................................................................... 370
How to insert, update, and delete data........................................................................ 372
••
XI I Expanded contents

Chapter 12 How to use JDBC to work with a database


How to work with JDBC .................................................................. 378
An introduction to database drivers ............................................................................ 378
How to connect to a database ..................................................................................... 380
How to return a result set and move the cursor through it ......................................... 382
How to retrieve data from a result set. ........................................................................ 384
How to insert, update, and delete data ........................................................................ 386
How to work with prepared statements ...................................................................... 388
The SQL Gateway application .......................................................390
The user interface ....................................................................................................... 390
The code for the JSP ................................................................................................... 392
The code for the servlet .............................................................................................. 394
The code for the utility class ....................................................................................... 398
How to work with connection pooling .......................................... 400
How connection pooling works .................................................................................. 400
How to make a connection pool available .................................................................. 400
How to implement a connection pool .........................................................................402
How to use a connection pool .....................................................................................404
The Email List application .............................................................406
The user interface .......................................................................................................406
The code for the JSP ...................................................................................................406
The code for the servlet .............................................................................................. 408
The code for the database class .................................................................................. 410
The code for the utility class ....................................................................................... 416

Chapter 13 How to use JPA to work with a database


An introduction to JPA ................................................................... 422
A summary of JPA implementations .......................................................................... 422
Entities and the entity manager .................................................................................. 422
How to configure NetBeans to work with JPA ........................................................... 424
How to configure a persistence unit. ........................................................................... 426
How to code JPA entities ............................................................... 428
How to code the class for an entity .. ........................................................................... 428
How to use getter and field annotations ...................................................................... 430
How to code relationships between entities ................................................................ 432
How to work with dates and times .............................................................................. 434
How to retrieve data........................................................................ 436
How to get an entity manager factory ......................................................................... 436
How to retrieve an entity by primary key ................................................................... 438
How to retrieve multiple entities ................................................................................. 440
How to retrieve a single entity .................................................................................... 442
How to modify data ......................................................................... 444
How to insert, update, or delete a single entity ..........................................................444
How to update or delete multiple entities ...................................................................446
A complete JPA class.....................................................................448
The methods that modify data ....................................................................................448
The methods that retrieve data ................................................................................... 450
•••
Expanded contents XIII

Section 4 Advanced servlet and JSP skills


Chapter 14 How to use JavaMail to send mail
An introduction to the JavaMail API ............................................. 460
How email works ........................................................................................................460
How to install the JavaMail APL................................................................................ 462
Code that uses the JavaMail API to send an email message ...................................... 464
How to create and send an email message ................................. 466
How to create a mail session ....................................................................................... 466
How to create a message ............................................................................................. 468
How to address a message .......................................................................................... 470
How to send a message ............................................................................................... 472
Example classes that send an email message ............................ 474
A helper class for sending an email with a local SMTP server.................................. 474
A servlet that uses a helper class to send an email message ...................................... 476
A helper class for sending an email with a remote SMTP server .............................. 480

Chapter 15 How to use SSL to work with a secure connection


An introduction to SSL ................................................................... 484
How SSL works........................................................................................................... 484
How TLS works .......................................................................................................... 484
When to use a secure connection................................................................................ 484
How SSL authentication works................................................................................... 486
How to get a digital secure certificate ........................................................................ 488
How to configure a testing environment for SSL ........................ 490
How to create a certificate for testing ......................................................................... 490
How to enable SSL in Tomcat..................................................................................... 492
How to test a local SSL connection ............................................................................ 492
How to work with a secure connection ........................................ 494
How to request a secure connection ........................................................................... 494
A JSP that uses a secure connection ........................................................................... 496
How to return to a regular HTTP connection ............................................................ 496
How to switch from a local system to an Internet server ........................................... 496

Chapter 16 How to restrict access to a web resource


An introduction to authentication ................................................. 502
How container-managed authentication works........................................................... 502
T hree types of authentication ..................................................................................... 504
How to restrict access to web resources ..................................... 506
How to add a security role .......................................................................................... 506
How to add a security constraint ................................................................................ 506
How to implement a security realm .............................................. 508
How to implement the UserDatabaseRealm ............................................................... 508
How to implement the JDBCRealm ........................................................................... 510
How to implement the DataSourceRealm .................................................................. 514
How to allow access to authorized users ..................................... 516
How to use basic authentication.................................................................................. 516
How to use digest authentication ................................................................................ 516
How to use form-based authentication ....................................................................... 518
XIV Expanded contents

Chapter 17 More security skills


An introduction to website security.............................................. 526
Common website attacks ............................................................................................ 526
How to prevent social engineering attacks ................................................................. 526
An introduction to cryptography ................................................................................ 528
Common password attacks ......................................................................................... 530
How to protect passwords ............................................................. 532
How to hash passwords ............................................................................................... 532
How to salt passwords ................................................................................................. 534
A utility class for hashing and salting passwords ....................................................... 536
How to enforce password strength requirements ....................................................... 538

Chapter 18 How to work with HTTP requests and responses


An introduction to HTTP ................................................................ 544
An HTTP request and response .................................................................................. 544
Common MIME types ................................................................................................ 546
Common HTTP request headers ................................................................................ 548
Common HTTP status codes ...................................................................................... 550
Common HTTP response headers .............................................................................. 552
How to work with the request ........................................................ 554
How to get a request header ........................................................................................ 554
How to display all request headers ............................................................................. 556
How to work with the response ..................................................... 558
How to set status codes ............................................................................................... 558
How to set response headers ....................................................................................... 558
Practical HTTP skills ...................................................................... 560
How to return a spreadsheet ....................................................................................... 560
How to control caching ............................................................................................... 560
How to compress a response with GZIP..................................................................... 562
How to return a binary file as an attachment ............................................................. 564
How to create virtual HTML pages............................................................................ 566

Chapter 19 How to work with listeners


How to use a ServletContextlistener ........................................... 572
How to code a class for the listener ............................................................................ 572
How to register the listener ......................................................................................... 574
How to code a JSP that uses the attributes set by the listener .................................... 576
How to work with other types of listeners.................................... 578
A summary of the listener interfaces ......................................................................... 578
The methods of the listener interfaces ........................................................................ 580
The methods of the event objects ............................................................................... 582

Chapter 20 How to work with fliters


An introduction to filters ................................................................ 588
How filters work .......................................................................................................... 588
Two benefits of filters .................................................................................................. 588
When to use filters ...................................................................................................... 588
How to add a filter ........................................................................... 590
How to code a filter ..................................................................................................... 590
How to configure a filter ............................................................................................. 592
Expanded contents XV

Two filter classes ............................................................................ 596


How to code a filter that performs request-side processing ....................................... 596
How to code a filter that performs response-side processing ..................................... 598
Other skills for workin,g with filters............................................... 600
How to wrap a request or response ............................................................................. 600
How to use an initialization parameter ....................................................................... 604
How to restrict access by IP address .......................................................................... 606

Chapter 21 How to work with JavaServer Faces


An introduction to JSF ................................................................... 614
A summary of JSF versions ........................................................................................ 614
How to add a JSF library to a project ......................................................................... 614
How to used managed beans ........................................................ 616
How to create a managed bean ................................................................................... 616
How to set the scope of a bean ................................................................................... 618
How to use standard JSF tags ...................................................... 620
How to code the head and body tags .......................................................................... 620
How to display data from a managed bean................................................................. 622
How to code the inputText tag .................................................................................... 624
How to validate data ................................................................................................... 626
How to code a form action .......................................................................................... 628
The Email List application ............................................................. 630
The user interface ....................................................................................................... 630
The EmailList bean..................................................................................................... 632
The index.xhtml file .................................................................................................... 634
The thanks.xhtml file .................................................................................................. 636

Section 5 The Music Store website


Chapter 22 An introduction to the Music Store website
The user interface ........................................................................... 644
The Home and Catalog pages ..................................................................................... 644
The code for the Home page ....................................................................................... 644
The business layer .......................................................................... 648
The class diagrams ...................................................................................................... 648
The Product class ........................................................................................................ 648
The controller layer......................................................................... 652
The CatalogController class ....................................................................................... 652
The structure ................................................................................... 656
The directory structure ............................................................................................... 656
The web.xml file ......................................................................................................... 658
The context.xml file .................................................................................................... 658
The database ................................................................................... 662
The database diagram ................................................................................................. 662
The SQL script for the database ................................................................................. 662
The data layer .................................................................................. 666
The class diagrams...................................................................................................... 666
The ProductDB class .................................................................................................. 666
XVI Expanded contents

The JPA version compared to the JDBC version ........................ 670


The similarities ........................................................................................................... 670
The differences ........................................................................................................... 670

Chapter 23 The applications of the website


The user interface for end users ................................................... 674
The Download application.......................................................................................... 674
The Cart application ................................................................................................... 674
The user interface for administrators ........................................... 680
The Ad min Login page ............................................................................................... 680
The Ad min Menu page ............................................................................................... 682
The Process Invoices application................................................................................ 684
The Reports application .............................................................................................. 684

Appendix A How to set up your PC for this book


How to install the source code for this book .............................................................. 692
How to install the JDK ............................................................................................... 694
How to install NetBeans ............................................................................................. 696
How to install Tomcat ................................................................................................. 698
How to configure a Tomcat server .............................................................................. 700
How to test NetBeans and Tomcat .............................................................................. 704
How to install MySQL ................................................................................................ 706
How to create the databases for this book .................................................................. 708
How to restore the databases for this book................................................................. 708

Appendix B How to set up your Mac for this book


How to install the source code for this book .............................................................. 712
How to install the JDK ............................................................................................... 714
How to install NetBeans ............................................................................................. 716
How to install Tomcat ................................................................................................. 718
How to configure a Tomcat server .............................................................................. 720
How to test NetBeans and Tomcat .............................................................................. 724
How to install the MySQL Community Server .......................................................... 726
How to install MySQL Workbench ............................................................................ 728
How to create the databases for this book .................................................................. 730
How to restore the databases for this book................................................................. 730
How to update the password for the root user ............................................................ 732
Introduction
Java servlets and JavaServer Pages (JSPs) came into widespread use in the
late 1990s. For many years, servlets and JSPs were the dominant technology for
building web applications, especially for large enterprises. Although servlets and
JSPs are no longer the dominant approach to web programming, they have some
advantages over other newer approaches. In addition, since there are still many
legacy web applications powered by them, servlets and JSPs will continue to be
relevant for many years to come.
A quick search on a typical job website shows that there is still plenty
of demand for servlet and JSP developers. In addition, many of the skills for
working with servlets and JSPs also apply to newer approaches to Java web
development such as JavaServer Faces (JSF). As a result, learning servlets and
JSPs is still a great way to get started with Java web programming.

Who this book is for


This book is for anyone who wants to learn how to develop web applications
using servlets and JSP. The only prerequisite is a basic understanding of the Java
programming language roughly equivalent to chapters 1 through 14 of our core
Java book, Murach's Java Programming. Once you have the necessary Java
skills, this book should work for you even if you have no experience developing
web applications.

Why you'll learn faster and better with this book


When we started writing this book, we knew we had to take a new approach
if we wanted to teach you everything you need to know in a way that's faster and
better than the other books. Here, then, are a few of the ways in which our book
differs from the others:
• Chapter 2 shows how to use the MVC pattern (or Model 2 architecture) to
get the most from JSPs and servlets. This allows you to use servlets when
they're appropriate and JSPs when they're appropriate. As a result, you
won't waste your time learning how to use servlets for tasks that should be
handled by JSPs, or vice versa.
•••
XVI 11 Introduction

• Chapter 3 shows how to use the NetBeans IDE with a Tomcat server to
develop web applications on your own computer. By using this IDE, you'll
learn faster and better than you would without one. In contrast, most
competing books leave you to figure this out on your own.
• Chapter 4 of this book provides a crash course in HTML5 and CSS3. Since
this is essential background for the use of JSPs, this means you won't have
to use a second book to figure out how HTML and CSS work.
• This book includes dozens of examples that range from the simple to
the complex. That way, you can quickly see how a feature works from
the simple examples, but you'll also see how the feature is used in more
complex, real-world examples, including the complete e-commerce
application that's presented in section 5.
• At the end of most chapters, you'll find exercises that help you practice what
you've learned. They also encourage you to experiment and challenge you to
apply what you've learned in new ways. To help you get the most practice in
the least time, you'll start these exercises from existing applications.
• If you page through this book, you'll see that all of the information is
presented in "paired pages," with the essential syntax, guidelines, and
examples on the right page and the perspective and extra explanation on the
left page. This helps you learn faster by reading less... and this is the ideal
reference format when you need to refresh your memory about how to do
something.

What you'll learn in this book


• In section 1, you'll learn the concepts and terms that you need for web
programming. You'll learn how to use the MVC pattern to structure your
web applications. And you'll learn how to use the NetBeans IDE with a
Tomcat server to develop servlets and JSPs for web applications. When
you're done with this section, you'll be ready to learn how to code and run
servlets and JSPs on your own computer.
• In section 2, you'll get a crash course in HTML and CSS, which is essential
to the use of JSPs. Then, you'll learn the skills for creating servlets and JSPs
that you'll need for almost every application. These chapters move from the
simple to the complex as they show you how to work with servlets, JSPs,
sessions, cookies, JavaBeans, Expression Language (EL), the JSP Standard
Tag Library (JSTL), and custom JSP tags.
• In section 3, you'll learn how to use both JDBC (an older access method)
and the newer Java Persistence API (JPA) to work with a database. Since
MySQL is a popular open-source database that is commonly used for web
applications, this section shows how to work with it, but these principles can
be applied to the use of any database.
Introduction XIX

• In section 4, you'll learn the advanced servlet and JSP skills that you
will need for certain types of web applications. This includes the use of
JavaMail, SSL, authentication, encryption, HTTP, listeners, and filters.
Then, it ends with an introduction to JavaServer Faces (JSF), an alternate
approach to JSP. Since we designed the chapters in this section to work
independently of each other, you can read them in any order you want. This
makes it easy to learn new skills whenever you need them.
• To complete your Java web programming skills, section 5 presents an
e-commerce website that puts the skills presented in the first four sections
into context. This downloadable application illustrates best practices
and provides code that you can use in your own applications. Once you
understand how this website works, you will have all the skills you need for
creating your own web applications.

What operating systems this book supports


The software you need for developing web applications with servlets and JSP
is available for Windows, Mac OS X, and Linux. If you're using Windows, you
can use appendix A to download and install this software. If you're using Mac
OS X, appendix B shows how to download and install this software. If you're
using another platform such as Linux, you probably already know how to install
this software! If not, you can use appendix B as a general guide and search the
Internet for more information if you need it.

How to get the software you need for this book


You can download all of the software that you need for this book for free
from the Internet. To make that easier for you, appendix A (PC) and B (Mac)
show how to download and install the software for this book. This software
includes Java SE, NetBeans, Tomcat, MySQL, and MySQL Workbench.

How our downloadable files make learning easier


To make learning easier, you can download the source code, files, and
databases for all the web applications presented in this book from our website
(www.murach.com). This includes the Music Store e-commerce application.
Then, you can view the complete code for these applications as you read each
chapter; you can compile and run these applications to see how they work; and
you can copy portions of code for use in your own web applications.
You can also download the starting points and solutions for the exercises
in this book. That way, you don't have to start every exercise from scratch.
This takes the busywork out of doing these exercises. As a result, you get more
practice in less time. In addition, if you encounter a problem, you can easily
check the solution. This helps you to keep moving forward with less chance that
you'll get stuck on a minor issue. For more information about these downloads,
please see appendix A (PC) or appendix B (Mac).
XX Introduction

Support materials for trainers and instructors


If you're a corporate trainer or a college instructor who would like to use
this book for a course, we offer an Instructor's CD that includes: (1) PowerPoint
slides, (2) test banks, (3) objectives, (4) additional exercises that aren't in this
book, (5) solutions to those exercises, (6) projects, and (7) solutions to those
projects.
To learn more about this Instructor's CD and to find out how to get it, please
go to our website at www.murach.com. Or, if you prefer, you can call Kelly at
1-800-221-5528 or send an email to [email protected].

Please let us know how this book works for you


When we started the first edition of this book, our goal was to teach you
how to develop real-world web applications with servlets and JSPs as quickly
and easily as possible. Now, with this third edition of this book, we hope we've
taken that to a new level. So if you have any comments, please email us at
[email protected].
Thanks for buying this book. Thanks for reading it. And good luck with your
web programming.

Joel Murach
Author
ection

Get started right


The three chapters in this section provide the background information that
you need for developing web applications with servlets and JavaServer
Pages (JSPs). In chapter 1, you'll learn what web programming is and how
servlets and JSPs work. In chapter 2, you'll learn how to use the MVC
pattern to structure a web application that uses servlets and JSPs.
Then, in chapter 3, you'll learn how to use the NetBeans IDE
(Integrated Development Environment) to work with the HTML, servlet,
JSP, and XML files that make up a servlet/JSP application. In addition,
you'll learn how to use NetBeans to run a Java web application on a
Tomcat server that's running on your computer.
An introduction to web
programming with Java
This chapter introduces some concepts and terms that you should learn before
you start web programming with servlets and JavaServer Pages (JSPs). In addi­
tion, it describes three approaches that you can use for developing Java web
applications. Finally, it describes some software that you can use to develop
and deploy serv let/JSP applications.

An introduction to web applications ....................................4


A typical web application ................................................................................4
The components of a web application .............................................................6
How static web pages work .............................................................................8
How dynamic web pages work ...................................................................... 10
Three approaches for Java web applications ................... 12
Servlet/JSP ..................................................................................................... 12
JSF.................................................................................................................. 12
Spring Framework ......................................................................................... 12
An introduction to servlet/JSP web development ............ 14
The software components.............................................................................. 14
The architecture ............................................................................................. 16
The standard directories and files ................................................................. 18
Software for developing Java web applications ...............20
IDEs for developing Java web applications ...................................................20
Web servers for Java web applications .......................................................... 22
Database servers for Java web applications................................................... 22
Tools for deploying Java web applications ................................................... 24
Perspective ...........................................................................26
4 Section 1 Get started right

An introduction to web applications


A web application is a set of web pages that are generated in response to
user requests. The Internet has many different types of web applications, such as
search engines, online stores, auctions, news sites, discussion groups, and games.

A typical web application


Figure 1-1 shows the first two pages of the shopping cart application that's
available from www.murach.com. Here, the first page presents some information
about our Java book. This page contains an Add To Cart link. When you click on
this link, the web application adds the book to your cart and displays the second
page, which shows all of the items in your cart.
The second page lets you change the quantity for an item or remove an item
from the cart. It also lets you continue shopping or begin the checkout process.
In this book, you'll learn all the skills you need to create a shopping cart applica­
tion like this one.
If you take a closer look at these web pages, you can learn a little bit about
how this application works. For the first page, the Address box of the browser
shows an address that has an htm extension. This means that the HTML code for
this page is probably stored in a file with an htm extension.
In contrast, the Address box for the second page shows the address of a
servlet that was mapped to the ordering/cart URL. This means that the HTML
code for this page was generated by a servlet. After the servlet address, you can
see a question mark and one parameter named productCode that has a value of
"htm5". This is the parameter that was passed from the first page.
Chapter 1 An introduction to web programming with Java 5

The first page of a shopping cart application


CJ @}

--
I:] Murach'sJava Progammi x

Cl
:=·
n1urach.cor11/books/javp/index.htm
Apps For quick acces�, place your bookmarks here on the bookmark� bar. Import bookmark� now... L] Other bookmarks

Home I Books I Dov,nloads I Trainers I Instructors I Customer Service I view cart I


Murach's Java Programming
by Joel t,lu ra ch
23 chapters, 802 pages, S40 illustrations
Published November 2011
ISBN: 978-1-890774-65-'3

Book price: S57.50; SAVE 30%, now just S4-0.25


eBook price: S47.50; SAVE 30%, nov, just S33.25
Book• eBook: S67.50; B-est Value! SAVE 30% 1 now Just 547.25

"f Jove your Java book. ft cuts :right to the essential information,
provjding the perfect balance betli'een too many details and too
little information. I bought another wel/-knovl'n Java book, but I
spent several hours trying to tearn what r learned from your book
in about 45 minutes." I add book I
I add ebook I
FREE do1Nnload of
sample chapters That's what one developer wrote us about an earlier edition of our
FREE download of the
�ook applications
core Java book. Now, you can expect th1at same practical, time­
saving approach in the current edition that covers the latest
I add both I
'.'\/hat soft,,vare you release of Java Standard Edition, Java SE 7 (or JDK 1.7).
More about the eBook
n��r1

The second page of a shopping cart application


CJ @}
Cl Mike Murach & AssociatE: x
Cl n1urach.cor11/ordering/cart?productCode = htmS --
:=· Apps For quick access, place your bookmarks here on the bookmark� bar. Import bookmark� now... L] Other bookmarks

Home I Books I Oov1nloads I Trainers I Instructors I Customer Service I view cart I


Your cart

Qty Description

!1 I [ Update I Murach's Java Programming [ Remove j


E � [ Update I Murach's HTML5 and CSS3 [ Remove j
To change the quantity, enter the new quantity and click on the Update button.

[ Continue Shopping ] I Proc eed t o Checkout ]

Do you have a pron1otion code to apply to this order?


If so, enter it here: [ =1
Other books related to what you just picked

Figure 1-1 A typical web application


6 Section 1 Get started right

The components of a web application


Figure 1-2 shows the basic components that make up a web application.
Because a web application is a type of c lientlserver application, the compo­
nents of a web application are stored on either the client computer or the server
computer.
To access a web application, you use a web browser that runs on a client
computer. One widely used web browser is Google Chrome, and a popular
alternative is Mozilla Firefox.
The web application itself is stored on the server computer. This computer
runs web server software that enables it to send web pages to web browsers.
Although there are many web servers, the Apache Software Foundation's Apache
HTTP Server is one of the most popular. Many developers refer to it just as
Apache.
Because most web applications work with data that's stored in a database,
most servers also run a database management system (DBMS), which is also
known as a database server. Two of the most popular for Java development are
MySQL and Oracle. When you use a database server, it doesn't have to run on
the same server as the web server software. In fact, a separate database server is
often used to improve an application's overall performance.
Although this figure shows the client and server computers connected via the
Internet, this isn't the only way a client can connect to a server in a web applica­
tion. If the client and the server are on the same Local Area Network (LAN), they
function as an intranet. Since an intranet uses the same protocols as the Internet,
a web application works the same on an intranet as it does on the Internet.
Chapter 1 An introduction to web programming with Java 7

Components of a web application


Client Server
computer computer

Internet

- connection
- I

Web Web server


browser Database server

Description
• Web applications are a type of client/server application. In a client/server applica­
tion, a user at a client computer accesses an application at a server computer. For a
web application, the client and server computers are connected via the Internet or
an intranet.
• In a web application, the user works with a web browser at the client computer. The
web browser provides the user interface for the application. One widely used web
browser is Google Chrome, but other web browsers such as Mozilla Firefox and
Internet Explorer are also widely used.
• A web application runs on the server computer under the control of web server
software. The Apache server is one of the most widely used web servers.
• For most web applications, the server computer also runs a database management
system (DBMS), which is also known as a database server. For servlet and JSP
applications, Oracle and MySQL are two of the most popular database management
systems.

Figure 1-2 The components of a web application


8 Section 1 Get started right

How static web pages work


HTML (Hypertext Markup Language) is the language that the browser
renders to the web pages that make up a web application's user interface. Some
web pages are static web pages, which are the same each time they are viewed.
In other words, they don't change in response to user input.
Figure 1-3 shows how a web server handles static web pages. The process
begins when a user at a web browser requests a web page. This can occur when
the user enters a web address into the browser's Address box or when the user
clicks a link that leads to another page. In either case, the web browser uses a
standard Internet protocol known as Hypertext Transfer Protocol (HTTP) to send
a request known as an HTTP request to the website's server.
When the web server receives an HTTP request from a browser, the server
gets the requested HTML file from disk and sends the file back to the browser
in the form of an HTTP response. The HTTP response includes the HTML
document that the user requested along with any other resources specified by the
HTML code such as graphics files.
When the browser receives the HTTP response, it renders the HTML
document into a web page that the user can view. Then, when the user requests
another page, either by clicking a link or typing another web address in the
browser's Address box, the process begins again.
Chapter 1 An introduction to web programming with Java 9

How a web server processes static web pages


Client Server
HTTP
request

HTTP
response

Description
• Hypertext Markup Language (HTML) is the language that the web browser converts
into the web pages of a web application.
• A static web page is an HTML document that's stored in a file and does not change
in response to user input. Static web pages have a filename with an extension of
.htm or .html.
• Hypertext Transfer Protocol (HTTP) is the protocol that web browsers and web
servers use to communicate.
• A web browser requests a page from a web server by sending the server a message
known as an HTTP request. For a static web page, the HTTP request includes the
name of the HTML file that's requested.
• A web server replies to an HTTP request by sending a message known as an HTTP
response back to the browser. For a static web page, the HTTP response includes
the HTML document that's stored in the HTML file.

Figure 1-3 How static web pages work


10 Section 1 Get started right

How dynamic web pages work


In contrast to a static web page, a dynamic web page changes based on the
parameters that are sent to the web application from another page. For instance,
when the Add To Cart button in the first page in figure 1-1 is clicked, the static
web page calls the web application and sends one parameter to it. Then, the web
application generates the dynamic web page and sends the HTML for it back to
the browser.
Figure 1-4 shows how this works. When a user enters data into a web page
and clicks the appropriate button, the browser sends an HTTP request to the
server. This request contains the address of the next web page along with any
data entered by the user. Then, when the web server receives this request and
determines that it is a request for a dynamic web page, it passes the request back
to the web application.
When the web application receives the request, it processes the data that the
user entered and generates an HTML document. Next, it sends that document to
the web server, which sends the document back to the browser in the form of an
HTTP response. Then, the browser displays the HTML document that's included
in the response so the process can start over again.
Chapter 1 An introduction to web programming with Java 11

How a web server processes dynamic web pages


Client Server
HTTP
request

HTTP
response

Description
• A dynamic web page is an HTML document that's generated by a web applica­
tion. Often, the web page changes according to parameters that are sent to the web
application by the web browser.
• When a web server receives a request for a dynamic web page, the server passes
the request to the web application. Then, the application generates a response, such
as an HTML document, and returns it to the web server. The web server, in turn,
wraps the generated HTML document in an HTTP response and sends it back to
the browser.
• Most modern web applications store and retrieve data from a database that runs on
a database server.
• The browser doesn't know or care whether the HTML was retrieved from a static
HTML file or was dynamically generated by the web application. Either way, the
browser displays the HTML document that is returned.

Figure 1-4 How dynamic web pages work


12 Section 1 Get started right

Three approaches
for Java web applications
There are many ways to develop Java web applications. Figure 1-5 describes
three approaches that are commonly used today. When developing Java web
applications, you typically use parts of the Java Enterprise Edition (Java EE)
specification. This specification describes how web servers can interact with all
Java web technologies including servlets, JavaServer Pages (JSP), JavaServer
Faces (JSF), Java Persistence API (JPA), Enterprise JavaBeans (EJB), and more.

Servlet/JSP
In a well-structured servlet/JSP application, servlets store the Java code that
does the server-side processing, and JavaServer Pages (JSPs) store the HTML
that defines the user interface. This HTML typically contains links to CSS and
JavaScript files. To run a web application that uses servlets and JSPs, you only
need to work with the servlet/JSP part of the Java EE specification.
Since the servlet/JSP API is a relatively low-level API, it doesn't do as much
work for the developer as the other two APis. However, the servlet/JSP API gives
the developer a high degree of control over the HTML, CSS, and JavaScript
that's returned to the browser. In addition, the servlet/JSP API is the foundation
for the other two approaches. As a result, it's a good place to get started with
Java web programming. As you progress through this book, you'll learn how to
develop servlet/JSP applications.

JSF
JavaServer Faces (JSF) is a newer technology that's designed to replace
both servlets and JSPs. It provides a higher-level API that does more work for
the programmer. When you use JSF, you typically use more Java EE features
than you do with the servlet/JSP approach.
When you use JSF, you can also use Enterprise JavaBeans (EJBs) to define
server-side components. Although there are some benefits to using EJBs, they're
overkill for most websites. As a result, this book doesn't show how to use them.

Spring Framework
Like JSF, the Spring Framework is a higher-level API that does more work
for the programmer than the servlet/JSP API. However, due to the way it's struc­
tured, the Spring Framework still gives the developer a high degree of control
over the HTML/CSS/JavaScript that's returned to the browser. As a result, if
control over HTML/CSS/JavaScript is a priority for your website, the Spring
Framework might be the right approach for you.
Chapter 1 An introduction to web programming with Java 13

Three approaches for developing Java web apps


Servlet/JSP
- Is a lower-level API that does less work for the programmer.
- Provides a high degree of control over the HTML/CSS/JavaScript that's
returned to the browser.
JSF
- Is a higher-level API that does more work for the programmer.
- Makes it more difficult to control the HTML/CSS/JavaScript that's returned to
the browser.
Spring Framework
- Is a higher-level API that does more work for the programmer.
- Provides a high degree of control over the HTML/CSS/JavaScript that's
returned to the browser.

Description
• The Java Enterprise Edition (Java EE) specification describes how web servers can
interact with all Java web technologies including servlets, JavaServer Pages (JSP),
JavaServer Faces (JSF), Java Persistence API (JPA), and Enterprise JavaBeans
(EJB).
• In a well-structured servlet/JSP application, servlets store the Java code that does
the server-side processing, and JavaServer Pages (JSPs) store the HTML that
defines the user interface. This typically includes links to the CSS and JavaScript
for the user interface.
• JavaServer Faces (JSF) is a newer technology than servlet/JSP that provides a
higher -level API that replaces both servlets and JSPs. For more on JSF, see chapter
21.
• Java Persistence AP/ (IPA) is an API for working with databases. It can be used
with servlet/JSP, JSF, or Spring. For more on JPA, see chapter 13.
• Enterprise JavaBeans (EJB) can be used to define server-side components. Since
these components are overkill for most websites, they aren't described in this book.

Figure 1-5 Three approaches for developing Java web apps


14 Section 1 Get started right

An introduction to servlet/JSP
web development
This topic introduces you to servlet/JSP development. In particular, it pres­
ents the software components, application architecture, and standard directories
that you typically use when you develop Java web applications.

The software components


Figure 1-6 shows the primary software components for a servlet/JSP web
application. By now, you should understand why the server must run web server
software. In addition, to work with servlets and JSPs, the server must also run a
servlet/JSP engine, which is also known as a servlet/JSP container. In this book,
you'll learn how to use the Tomcat server. This server is one of the most popular
servers for Java web applications, and it includes both a web server and a
servlet/JSP engine.
For a servlet/JSP engine to work properly, the engine must be able to access
the Java Development Kit (JDK) that comes as part of the Java Standard Edition
(Java SE). The JDK contains the Java compiler and the core classes for working
with Java. It also contains the Java Runtime Environment (IRE) that's necessary
for running compiled Java classes. Since this book assumes that you already
have some Java experience, you should already be familiar with the JDK and the
JRE.
Since all servlet/JSP engines must implement the servlet/JSP part of the Java
EE specification, all servlet/JSP engines should work similarly. In theory, this
makes servlet/JSP code portable between servlet/JSP engines and application
servers. In practice, though, there are minor differences between each servlet/JSP
engine and web server. As a result, you may need to make some modifications to
your code when switching servlet/JSP engines or web servers.
Since most servlet/JSP web applications store their data in a database, the
server typically runs a database server too. In this book, you'll learn how to use
MySQL as the database server. This software is open-source and commonly used
with servlet/JSP applications.
Chapter 1 An introduction to web programming with Java 15

The components of a servlet/JSP application


Client

HTTP HTTP
request response

Server

Description
• A servlet/JSP application must have a web server and a servlet/JSP engine, also
known as a servlet/JSP container, to process the HTTP request and return an HTTP
response, which is typically an HTML page. Most servlet/JSP applications use
Tomcat as both the web server and the servlet/JSP engine.
• Most servlet/JSP applications use a database to store the data that's used by the
application. Many servlet/JSP applications use MySQL as the database, though
there are many other databases to use.
• For a servlet/JSP engine to work, it must have access to Java's Java Development
Kit (JDK), which comes as part of the Java Standard Edition (Java SE). Among
other things, the JDK contains the core Java class libraries, the Java compiler, and
the Java Runtime Environment (IRE).

Figure 1-6 The components of a servlet/JSP application


16 Section 1 Get started right

The architecture
Figure 1-7 shows the architecture for a typical web application that uses
servlets and JSPs. This architecture uses three layers: (1) the presentation layer,
or user interface layer, (2) the business rules layer, and (3) the data access
layer. In theory, the programmer tries to keep these layers as separate and
independent as possible. In practice, though, these layers are often interrelated,
and that's especially true for the business and data access layers.
The presentation layer consists of HTML pages and JSPs. Typically, a web
designer works on the HTML stored in these pages to create the look and feel of
the user interface. Later, a Java programmer may need to edit these pages so they
work properly with the servlets of the application.
The business rules layer uses servlets to control the flow of the application.
These servlets may call other Java classes to store or retrieve data from a data­
base, and they may forward the results to a JSP or to another servlet. Within the
business layer, Java programmers often use a special type of Java class known as
a JavaBean to temporarily store and process data. A JavaBean is typically used
to define a business object such as a User or Invoice object.
The data layer works with the data of the application on the server's disk.
Typically, this data is stored in a relational database such as MySQL. However,
this data can also be stored in text files, binary files, and XML files. Or, it can
come from web services running on the other servers.
Chapter 1 An introduction to web programming with Java 17

The architecture for a typical servlet/JSP application


Presentation layer

Business rules layer

Data access layer

Description
• The presentation layer for a typical servlet/JSP web application consists of HTML
pages and JSPs.
• The business rules layer for a typical servlet/JSP web application consists of
servlets. These servlets may call other Java classes including a special type of Java
class known as a JavaBean. As you progress though this book, you'll learn how to
use several special types of tags within a JSP to work with JavaBeans.
• The data access layer for a typical Java web application consists of classes that
read and write data that's stored on the server's disk drive.
• For most web applications, the data is stored in a relational database such as
MySQL. However, it may also be stored in binary files, text files, or XML files.

Figure 1-7 The architecture for a servlet/JSP web application


18 Section 1 Get started right

The standard directories and files


Figure 1-8 shows a simplified version of the directory structure for the
Music Store application that's presented at the end of this book. Some of these
directories are part of the servlet and JSP specifications. As a result, they are
standard for all web applications. For example, all web applications that use
servlets must have the WEB-INF and WEB-INF\classes directories. In addition,
you can optionally include other standard directories such as the WEB-INF\lib
directory or the META-INF directory.
Of course, to organize and structure an application, a programmer can create
other directories within these directories. In this figure, for example, the admin,
cart, and download directories organize the Administration, Cart, and Download
sections of the Music Store application.
To start, each web application must have a root directory. This directory
can be referred to as the document root directory, or just document root. In this
figure, the document root directory is named musicStore, and it is subordinate
to Tomcat's webapps directory. Then, all of the other directories and files for the
application must be subordinate to this document root directory.
The WEB-INF directory that's subordinate to the document root directory
typically contains a web.xml file for the application. You'll learn more about
this file in the next chapter. In addition, you can use this directory or any of its
subdirectories to store files that you don't want to be directly accessible from the
web. For example, some applications in this book use the WEB-INF directory to
store data files. This prevents users from directly accessing these files.
The WEB-INF directory also has a few standard directories that are subor­
dinate to it. In particular, the WEB-INF\classes directory is the root directory
for all Java classes for the application that aren't stored in JAR files, including
servlets. Typically, these are the classes that you write. In contrast, the
WEB-INF\lib directory contains the JAR files that contain any Java class librar­
ies for the application. Typically, you get these JAR files from a third party.
Remember, though, that Tomcat's lib directory stores the JAR files for the class
libraries that are available to all web applications running on the web server. As a
result, you only use the WEB-INF\lib directory if you want to make the JAR file
available to just that one application.
To organize the classes that you create for the application, you can store
them in packages. In that case, you need to create one subdirectory for each
package. For example, this figure shows five packages. T hree of these packages
(music.admin, music.cart, and music.download) contain servlets that work with
the Administration, Cart, and Download sections of the application while the
other two contain the Java classes that provide the business objects
(music.business) and data access objects (music.data) for the application.
As you progress through this book, you'll learn how to use some other
standard directories and files to deploy web applications. For example, if you
want to use the database connection pool that's available from Tomcat, you can
modify the context.xml file that's stored in the META-INF directory as described
in chapter 12. For now, though, this figure should give you a general idea of what
it takes to deploy a web application.
Chapter 1 An introduction to web programming with Java 19

The directory structure for a web application named musicStore


W tomcat
:...... webapps
:......• musicStore (the root directory for HTML and JSP files)
····· admin
····· cart
····· catalog
···· META-INF (content.xml file)
:
:....• WEB-INF (the web.xml file)
:...... classes (the root directory for Java classes)
:......• music
business
controllers
.. . . . data
. ····· util
i ......• lib (JAR files for Java class libraries)

A summary of the directories and files for a web application


Directory Description
(root) This directory and its subdirectories typically contain the
HTML and JSP files for the application.
\WEB-INF This directory typically contains a file named web.xml.
You can use this file to configure the servlets and other
components that make up the application. In addition, this
directory is not directly accessible from the web.
\WEB-INF\classes This directory and its subdirectories contain the servlets
and other Java classes for your application. Each subdirec­
tory must correspond with the package for the Java class.
\WEB-INF\lib This directory contains any JAR files that contain Java
class libraries that are used by the web application.
\META-INF This directory contains the context.xml file. You can use
this file to configure the web application context.

Description
• The top-level directory for a web application is known as its root directory.
• A Java web application is a hierarchy of directories and files in a standard layout
defined by the Java EE specification. All Java web applications must use the first
three directories that are summarized above.
• To make classes within a JAR file availa ble to more than one web application, you
can put the JAR file in Tomcat's lib directory.

Figure 1-8 The standard directories and files for a servlet/JSP web application
20 Section 1 Get started right

Software for developing Java


web applications
This topic presents some of the software options that you have for develop­
ing Java web applications.

IDEs for developing Java web applications


In the early days of Java web programming, programmers commonly used
text editors to enter, edit, compile, and test the HTML, JSP, Java, servlet, and
XML files that make up a web application. Today, however, many Integrated
Development Environments (IDEs) are available that make Java web program­
f
ming more ef icient.
Two of the most popular IDEs for developing Java web applications are
NetBeans and Eclipse. Both are open-source, and both are available for free.
Of the two, we think that NetBeans is easier to use, especially when you're
getting started with web programming. That's why we recommend that you use
NetBeans with this book.
In figure 1-9, for example, you can see the NetBeans IDE with the project
for chapter 2 in the Projects window, the code for a servlet class in the editor
window, and runtime messages in the Output window. This is similar to what
you'll find in most IDEs. As a result, once you're done with this book, you can
easily apply the skills that you learn with NetBeans to another IDE.
Although we recommend using NetBeans with this book, you should be able
to use another IDE with this book if you prefer. To do that, though, you will need
to figure out how to import the source code for this book into your IDE so you
can compile and run the sample applications and complete the exercises. In addi­
tion, you will need to use your IDE to perform the tasks presented in chapter 3.
Since the JDK, N etBeans, Tomcat, and MySQL can be run by most operat­
ing systems, Java web developers aren't tied to a specific operating system. In
fact, developers often use Windows or Mac OS X during development. However,
when the applications are ready for release, they are often deployed to a Linux or
Unix server.
Chapter 1 An introduction to web programming with Java 21

The NetBeans IDE


0 ch02e-mail - NetBe-ans IOE B.O I= I @J :·
cv, I

File Edit View Navigate Source Re-factor Run Debug Profile Team Tools Window Help IQ.• Search (Ctrl+I)

Projects • Files I I Services I g


� index.html •I� I
x Ll:!IIL.-�...;...;�-1..
Emaillistservlet.java rll1 thanks.jsp i:& I 818 G@J
s-� ch02email I '1? �
�����������������__,::::::::....:::...::::,
% I <::iii �� I O D 11/Q! !
I� •
Source History I � (B • � • I to_ '¢ � � :::::� I EB
$m Web Pages package murach.email;
! El META-INF �
! iii � WEB-INF 3 S import java.io. ";
i 13...� styles 4 import javax.servlet.*;
i !· [!I
! L....�
index.html
thanks.jsp
s import javax. servlet.http."; -
6
$@ Source Packages 7 import murach.business.User; -
! El··· E!3 murach.business
e - import m.urach.data.OserDB;
i iii § murach.data 9
! El
§3 murach.email 10 public class EmailLi.stSerwlet extends HttpServlet {
i L. Ii E maillistservlet.java 11
$ (R "J:est Packages 12 @override
9.. � Libraries @ protected void doPost(HttpServletRequest request,
i:p � TestL1braries 14 HttpServletResponse response)
El··� Configuratiori Files 1s G throws ServletException, IOException {
i!J-� ch04email

do Post - Navigator x I
16
17 String url = "/index.htnl"; -
..-11 ..-1
Q
18
Members <empty> LaJ 19 t/ get c�rre�t act10�
&'.> Emaillistservlet : : HttpServlet 20 String action= request.getParameter("action"); ...
!·· 'ft:>
doGet(HttpSe-rvletRequestrequest, H
L.t:J doPost(HttpServletRequest request, I :===::;::: = ===============
t)
� Emaillistservlet )

Output I Ii
=============== =======:
doPost ) url ) X

• ch02emai (run) n I Tomcat 8.0 Log R I Tomcat8.0 ae I


• J .o--��.��������������-����--,
11-Apr-2014 15: 48: 44 _394 INFO (:m&i. n] erg_ apac:h@ _ceyetoLAb:!ltrac:tPretocel _!ltart Starting Protoc:oll •
11-Apr-2014 15: 48: 44 _ 399 INFO (:m&i.n] erg_apac:h@ _ cata.lina _,.ta.rtup.Catali.na_ :!ltart S@rv@r Bta.rtup :
11-Apr-2014 15:48:46_047 INFO lihttp-nio-8080-exec-41 org_apache_catalina_core_StandardContext.r1
11-Apr-2014 15: 48: 47. l 7f> INFO llhttp-nio-8080-exec-4 I org .apache- ca:calina._ c:ore. Sta.nda.rdContext. rc
c::::i

�1 rrr J

17:36 I INS

Popular IDEs for Java web development


NetBeans
Eclipse
IntelliJ IDEA

Description
• An Integrated Development Environment (/DE) is a tool that provides all of the
functionality that you need for developing web applications.
• NetBeans and Eclipse are popular IDEs for Java web development that are
open-source and free.
• Chapter 3 shows how to use NetBeans for developing Java web applications. We
recommend using this IDE with this book.

Figure 1-9 IDEs for developing Java web applications


22 Section 1 Get started right

Web servers for Java web applications


Figure 1-10 describes two popular web servers for Java web applications.
This book shows how to use the Tomcat server, which is the most popular server
for Java web applications. Tomcat includes a web server named Coyote and a
servlet/JSP engine named Catalina. As a result, this server can work with the
servlet/JSP part of the Java EE specification.
In contrast, the GlassFish server implements the complete Java EE specifica­
tion. Since it's more than just a servlet/JSP engine, it's known as an application
server. The advantage of using an application server like GlassFish is that it
provides more features for working with other parts of the Java EE specification
such as JSF and JPA. One disadvantage is that it requires more system resources
than Tomcat. As a result, it may not run as quickly on your computer.
This figure also lists four other popular web servers for Java applications.
These web servers include WildFly, which was formerly known as JBoss, Jetty,
Oracle WebLogic, and IBM WebSphere. Each server implements some or all of
the Java EE specification, and each server has its advantages and disadvantages.

Database servers for Java web applications


This figure also describes the most popular database server for Java web
applications, the MySQL database server. This is the database server that you'll
learn to use in this book. Like Tomcat and GlassFish, MySQL is open-source
and runs on all modern operating systems. In addition, MySQL implements most
of the SQL standard. As a result, database code developed for the MySQL server
should be mostly portable between database servers.
Although many Java web applications use a MySQL database, some devel­
opers prefer other open-source databases, such as PostgreSQL. On the other
hand, some large enterprises prefer using a proprietary database like Oracle to
store mission-critical data.
Chapter 1 An introduction to web programming with Java 23

Two popular web servers


Tomcat
- Is a servlet/JSP engine that includes a web server.
- Is free, open-source, and runs on all modern operating systems.
- Is a popular web server for Java web applications.

GlassFish
- Is a complete Java EE application server.
- Is free, open-source, and runs on all modern operating systems.
- Provides more features than Tomcat.
- Requires more system resources than Tomcat.

Other popular web servers


- WildFly (formerly JBoss)
- Jetty
- Oracle WebLogic
- IBM WebSphere

A popular database server


MySQL
- Is a relational database server that implements most of the SQL standard.
- Is free, open-source, and runs on all modern operating systems.
- Is the most popular database server for Java web applications.

Other popular database servers


- PostgreSQL
- Oracle

Description
• A servlet/JSP engine is the software that allows a web server to work with the
servlet/JSP part of the Java EE specification.
• Tomcat is one of the most popular servlet/JSP engines. It includes a web server
named Coyote and a servlet/JSP engine named Catalina.
• A Java EE application server is the software that allows the web server to work
with the entire Java EE specification including servlets, JSP (JavaServer Pages),
JSF (JavaServer Faces), JPA (Java Persistence API), EJB (Enterprise JavaBeans),
and so on.
• GlassFish is one of the most popular application servers. It includes a web server, a
servlet/JSP engine that's based on Tomcat's servlet/JSP engine, and more.
• MySQL is one of the most popular database servers.

Figure 1-10 Web and database servers for Java web applications
24 Section 1 Get started right

Tools for deploying Java web applications


Once you've tested your servlets and JSPs on your own computer or an
intranet, you may want to deploy your web application on the Internet. To do
that, you need to get a web host. One way to do that is to find an Internet service
provider (ISP) that provides web hosting that supports servlets and JSPs. If you
read the text for the ISP on the web page shown in figure 1-11, for example, you
can see that this ISP supports servlets and JSPs.
If you search the web, you'll be able to find many other ISPs and web hosts.
Just make sure that the one you choose not only supports servlet and JSP devel­
opment, but also the database management system that your application requires.
When you select a web host, you get an IP address like 64.71.179.86 that
uniquely identifies your website (IP stands for I nternet Protocol). Then, you can
get a domain name like www.murach.com. To do that, you can use any number
of companies that you can find on the Internet. Until you get your domain name,
you can use the IP address to access your site.
After you get a web host, you need to transfer your files to the web server.
To do that, you can use File Transfer Protocol (FTP). The easiest way to use
FTP is to use an FTP client such as the FileZilla client shown in this figure. An
FTP client like this one lets you upload files from your computer to your web
server and download files from your web server to your computer.
Chapter 1 An introduction to web programming with Java 25

An ISP that provides web hosting that supports servlets and JSPs
E] JSP Web Hosting and Sel'\ )(

C [j www.mmaweb.net --
•••
:· Apps For quick access, place your bookmarks here on the bookmarks bar. Import bookmarks now ... D Other bookmarks

web bostios sales FAQs Account Log11


(716) 689-1593

,-. HOHE HOSTING SERVICES S\JPPORT ORDER A.BOUT US SOFTWARE

Private JVM with Every


Account!
Don't have a domain yet? See if
yours is available by checking
our whois gateway:

Domain (.com. .net, .org)

L I ,--1 $49.99
--.
C-h e- ck j JSP hosting and servlet hosting accounts ·with CCOUNT
per..-.Ch'
advanced, scalable server technologies like Servlets,
Java Server Pages (JSP). Enterprise JavaBeans
(EJB) and XML are what MMA specializes in.
Java Developer Links
The result is a continuous upgrade • Plu, one-month setup fee st
• SeNlets.com
path that lets small businesses ,isJt of first month.
launch websites built on proven
• JsvaWotld
technology that can grow as you
• Official SeNlet Home achieve success without the need
• JsvaSeN!H Pages Home
_.......,_
to rebuild and redeploy your core

The FileZilla program


fi) murach.com - classes - [email protected] m - FileZilla
File Edit Vi� Transfer Server Bookmarks. Help

I � ·ILC1iltiiJI � -. 13 �I��� n
I Host:
Status:
Respoose:
User.name: Password:
Connection established, waiting for welcome message ...
227 Entering Passive !Mode (72,9,137,30, 138,150)
Port: [ Quick.connect ] r:;l
-
Command: MLSD
Response: 150 Accepted data connection
Respoose: 226-0ptions: ..a�
Response: 226 4 matches total D
Status: !Directory listing successful

Local site: 1t\Web Site'vnurach_web4\/:,uild'"'eb\\�/EB-,INF\dassesvnurach\fv\ ..- Remote site: /htclocs/WEB-INF/dasses/mur.ach/fv


,customers j ... ?, customers
,custserv I ... ? custserv
downloads D L. .? downloads D
.... /..... • fv

fv
i
Filename Filesize Filetype Filename Filesize Filetype
- ..
D Financial Calculations.class 747 CLASS File D Financial Calculations.class 747 CLASS Fil
Dlliliiiilli lllliltilli LJ FutureValueServlet.class 2,389 CLASS Fil

m
t-----
" < I Ill
Selected 1 file. Total size: 2,389 Open 2 files.Total size: 3,136 byte.s
Edit
Server/local file Size Priority Status
Create directory
Refresh

Queued files Failed tra Delete


Rename
[!] IHI Queue: empty

Figure 1-11 Tools for deploying Java web applications


26 Section 1 Get started right

Perspective
The goal of this chapter has been to provide the background that you
need for developing servlets and JSPs. Now, if this chapter has succeeded,
you should be ready to learn how to use the MVC pattern to structure a web
application.

Summary
• A web application is a set of web pages that are generated in response to
user requests.
• To run a web application, the client requires a web browser and the server
requires web server software. The server may also require a database
management system (DBMS).
• Hypertext Markup Language (HTML) is the language that the browser
converts into the web pages of a web application, while Hypertext Transfer
Protocol (HTTP) is the protocol that web browsers and web servers use to
communicate.
• A web browser requests a page from a web server by sending an HTTP
request. A web server replies by sending an HTTP response back to the
browser.
• A static web page is generated from an HTML document that doesn't
change, while a dynamic web page is generated by a web application based
on the parameters that are included in the HTTP request.
• The Java Enterprise Edition (Java EE) specification describes how web
servers can interact with all Java web technologies.
• A servlet/JSP engine is the software that allows a web server to work with
the servlet/JSP part of the Java EE specification.
• Tomcat is one of the most popular servlet/JSP engines, and most servlet/JSP
applications use Tomcat as both the web server and the serv let/JSP engine.
• An application server is the software that allows the web server to work
with the entire Java EE specification.
• To run Java web applications, the server requires the Java Development
Kit (JDK), a web server, and a servlet/JSP engine. This allows the server to
process the HTTP request and return an HTTP response.
• Most servlet/JSP applications use a database such as MySQL to store the
data that's used by the application.
• As you develop a Java web application, you try to divide its classes into
three layers: presentation, business rules, and data access. This makes it
easier to maintain the application.
• The top-level directory for a web application is known as its root directory.
Chapter 1 An introduction to web programming with Java 27

• An Integrated Development Environment (/DE) is a tool that provides most


of the functionality that you need for developing web applications.
• NetBeans and Eclipse are popular IDEs for Java web development. Both are
open-source, free, and work on all modern operating systems.
• To deploy your web application on the Internet, you can get an Internet
service provider (ISP) that provides web hosting that supports servlets and
JSPs.
• When a web application runs on the Internet, it has an IP (Internet Protocol)
address like 64.71.179.86 and a domain name like www.murach.com. These
addresses provide two ways to uniquely identify the website.
• To transfer your web application files to a web server, you can use a File
Transfer Protocol (FT P) client such as FileZilla.
How to structure
a web application
with the MVC pattern
This chapter begins by presenting two patterns that you can use for
servlet/JSP web development. Then, it shows how to use the second pattern,
which is known as the MVC pattern, to structure a web application. There
are several advantages to this approach, and it's generally considered a best
practice.

Two p atterns for servlet/JSP app lications ........................ 30


The Model 1 pattern ...................................................................................... 30
The Model 2 (MVC) pattern.......................................................................... 32
A servlet/JSP application that uses the MVC pattern ...... 34
The user interface .......................................................................................... 34
The HTML for the first page ......................................................................... 36
The CSS for both web pages.......................................................................... 38
The servlet for the back-end processing ....................................................... 40
The web.xml file ............................................................................................ 42
The User class ............................................................................................... 44
The JSP for the second page ......................................................................... 46
Persp ective ...........................................................................48
30 Section 1 Get started right

Two patterns
for servlet/JSP applications
A pattern is a standard approach that programmers use to solve common
programming problems. This topic describes two patterns that you can use when
you develop Java web applications. However, for a serious web application, most
developers consider the second pattern to be a best practice and recommend
avoiding the first pattern.

The Model 1 pattern


The Model 1 pattern that's shown in figure 2-1 uses a JSP to handle both
the request and response of the application. In addition, the JSP does all of the
processing for the application.
To do that, the JSP interacts with Java classes and objects that represent the
data of the business objects in the application and provide the methods that do
the business processing. In this figure, for example, the application stores the
data for a user in a User object.
To save the data of the business classes, the application maps the data to a
database or files that can be called the data store for the application. This is also
known as persistent data storage because it exists after the application ends.
Usually, data access classes like the UserDB class shown in this figure store the
data of the business objects in a database. Later in this book, you'll learn two
ways to create data access classes like this one.
Although the Model 1 pattern is sometimes adequate for applications that
have limited processing requirements, this pattern is not recommended for most
applications. As a result, it isn't presented in this book.
Another random document with
no related content on Scribd:
The Project Gutenberg eBook of The 42nd
(East Lancashire) Division 1914-1918
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: The 42nd (East Lancashire) Division 1914-1918

Author: Frederick P. Gibbon

Release date: May 5, 2024 [eBook #73544]

Language: English

Original publication: United Kingdom: George Newnes, Ltd, 1920

Credits: Brian Coe and the Online Distributed Proofreading Team at


https://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK THE 42ND (EAST


LANCASHIRE) DIVISION 1914-1918 ***
THE
42ND (EAST LANCASHIRE)
DIVISION
1914-1918

First published in 1920

Printed Great Britain by Richard Clay & Sons, Limited,


in
brunswick st., stamford st., s.e. 1, and bungay, suffolk.
MAJOR-GENERAL SIR WM. DOUGLAS, K.C.M.G., C.B., D.S.O.

By permission of Lyddell Sawyer.


The
42nd (East Lancashire) Division
1914-1918

BY
FREDERICK P. GIBBON
Author of “The Lawrences of the Punjab”

LONDON
PUBLISHED AT THE OFFICES OF “COUNTRY LIFE,” LTD.,
20 TAVISTOCK STREET, COVENT GARDEN, W.C. 2, AND BY
GEORGE NEWNES, LTD., 8-11 SOUTHAMPTON STREET,
STRAND, W.C. 2
NEW YORK: CHARLES SCRIBNER’S SONS
To the
Officers, Warrant Officers,
Non-Commissioned Officers, and Men
of the
42nd (East Lancashire) Division
As their late Commander, I dedicate this history of their
achievements, conspicuous even in days of great deeds, in the hope
that the record of their unchanging spirit of courage, loyalty, and
comradeship may give gratification to survivors and solace to
relatives of the fallen.
11th
November
, 1920.
MAJOR-GENERAL A. SOLLY-FLOOD, C.B., C.M.G., D.S.O.

By permission of Keturah Collings.


FOREWORD
The 42nd (East Lancashire) Division was only a comparatively
short time under my command, but during that period officers,
N.C.O.s and men showed themselves to be possessed of a
magnificent fighting spirit.
The 42nd Division came to France at a time of crisis, and shared
in the glory of breaking the most desperate and most dangerous
German offensive made since the early days of the war. In my
Despatches I have drawn attention to some of the outstanding
actions of the Division. I am glad now to express to all ranks my
personal gratitude for their splendid service.

Field Marshal.
G.H.Q. The Forces in Great Britain,
Horse Guards, London, S.W. 1.
14th July, 1919.
PREFACE
“Sir William Douglas asks me ‘to write a few lines’ to be embodied
in the preface to a history of the 42nd Division.
“In the regions of time and space the Dardanelles enterprise forms
only a trifling part of the record of this famous Division; but, in the
sphere of the imagination, that part will be reckoned by Lancastrians
yet unborn as the most precious heirloom bequeathed to them by
the generation who fought the great war.
“Why? I will give the reasons in the words of a gallant young
Australian killed shortly after he wrote me as follows from the front
in France: ‘I often compare the two situations: out here and on
those wild romantic shores of the Ægean; I compare them and I find
that the Peninsula war stands quite alone and apart, an ineffaceable
memory.’
“Bearing in mind that I am limited to a few lines I propose to think
out nothing new, but to repeat now what was jotted down about a
sample of the 42nd Division at the time (the 4th June, 1915), in my
post of command, shared that day with two enormous tarantulas—
“On the right the French rushed the ‘Haricot’—so long a thorn in
their flesh; next to them the Anson lads stormed another big Turkish
redoubt in a slap-dash style reminding me of the best work of the
old Regular Army; but the boldest and most brilliant exploit of the lot
was the charge made by the Manchester Brigade in the centre who
wrested two lines of trenches from the Turks; and then, carrying
right on to the lower slopes of Achi Baba, had nothing between them
and its summit but the clear, unentrenched hillside. They lay there—
the line of our brave lads, plainly visible to a pair of good glasses—
there they actually lay! We wanted, so it seemed, but a reserve to
advance in their support and carry them right up to the top. We said
—and yet could hardly believe our own words—‘We are through!’
“Alas, too previous that remark. Everything began to go wrong.
First the French were shelled and bombed out of the ‘Haricot’; next
the right of the Naval Division became uncovered and they had to
give way, losing many times more men in the yielding than in the
capture of their ground. Then came the turn of the Manchesters, left
in the lurch, with their right flank hanging in the air. By all the laws
of war they ought to have tumbled back anyhow, but by the laws of
the Manchesters they hung on and declared they could do so for
ever....

General,
“Lieutenant of the Tower of London.”
1st September, 1919.

The foregoing words were written by the Commander-in-Chief


under whom the 42nd (East Lancashire) Division went into action for
the first time of its existence. It is nearly a year now since Sir Ian
Hamilton wrote them; this will give the reader some idea of the
gigantic task those who have collected the material for, and the
writer of, this book have had.
The work is an attempt to record the doings and follow the
fortunes of the 42nd (East Lancashire) Division in the Great War, but
nothing that can be written can adequately disclose the noble
manner in which these lads preserved throughout that dogged
courage and insistent resolution from which it was impossible, for
those who were present, to withhold their admiration. My own four
years’ experience of them has left me with the deepest feelings of
pride and affection. From first to last they proved themselves to be
gallant, loyal and self-sacrificing soldiers, warm-hearted, responsive
and lovable men.
The thanks of the Committee responsible for the publication of
this book are due to Captain E. R. Streat and Mr. George Bigwood,
who collected much of the data, but more especially to Mr. F. P.
Gibbon, who so kindly consented to write the History. The labour of
collecting information from War Diaries and comparing the various
accounts which so many old members of the Division have been kind
enough to send him, has been very great, and we owe Mr. Gibbon a
debt of deep gratitude.

7th August, 1920.

The Committee and the Author wish to record their warm


appreciation of the assistance given in the compiling of this History
by many Officers, Non-commissioned Officers and Men of the
Division.

As the final proofs of the book were being passed, there came the
sad news of the death of the first Divisional Commander, Major-
General Sir William Douglas, K.C.M.G., C.B., D.S.O., at Cultz, near
Aberdeen, on November 2nd, 1920. He had come to be regarded as
the Father of the Division. It was under him that it earned the
distinction of being the first Territorial Division to leave these shores,
and under him it received its baptism of fire. Even when he had
passed from command—both during the war and after hostilities had
ceased—his interest in the welfare of all ranks remained unabated,
and the affection he felt towards them was warmly reciprocated.
In expressing their deep sorrow and their sympathy with Lady
Douglas, the Committee feel that they may speak for all ranks and
all services of the Division.
CONTENTS
CHAP. PAGE
I. LANCASHIRE AND EGYPT (AUGUST 1914—MAY 1915) 1
II. GALLIPOLI (MAY 1915) 19
III. GALLIPOLI (JUNE 1915—JANUARY 1916) 34
IV. THE SUEZ CANAL AND SINAI (JANUARY 1916—MARCH
1917) 63
V. FRANCE (MARCH—AUGUST 1917) 86
VI. YPRES (SEPTEMBER 1917) 97
VII. NIEUPORT (OCTOBER—NOVEMBER 1917) 106
VIII. LA BASSÉE (DECEMBER 1917—MARCH 1918) 114
IX. OPENING OF THE GERMAN OFFENSIVE (MARCH 21—
APRIL 8, 1918) 128
X. ENTR’ACTE (APRIL 9—AUGUST 20, 1918) 142
XI. THE BEGINNING OF THE END (AUGUST 21—
SEPTEMBER 6, 1918) 155
XII. THROUGH THE HINDENBURG LINE (SEPTEMBER 7—30,
1918) 171
XIII. ACROSS THE RIVER SELLE (OCTOBER 9—23, 1918) 179
XIV. FORÊT DE MORMAL AND HAUTMONT (NOVEMBER 3—
11, 1918) 191
ROLL OF HONOUR 200
HONOURS AND AWARDS 232
HEADQUARTERS STAFF AND OFFICERS COMMANDING
UNITS 242
KEY MAP SHEWING APPROXIMATE POSITIONS OF BATTLE FRONTS OCCUPIED BY
THE 42ND DIVISION (E. Lancs. T.)
MOVEMENTS FROM OUTBREAK OF
WAR UNTIL ARMISTICE
1914-1915
Sept.-May British Army of Occupation in Egypt, and
on Suez Canal Defences.
1915-1916
May-Jan. M.E.F. At Cape Helles, Gallipoli Peninsula.
1916-1917 E.E.F. Suez Canal Defences and Sinai Peninsula.
Jan.-Feb. Advance through Romani to El Arish.
1917
Feb. and March B.E.F. Arrived at Marseilles and proceeded to
neighbourhood of Abbéville.
May In the line at Epéhy and Lempire.
June ” ” Havrincourt Wood and
Trescault.
Aug. and Sept. ” ” Ypres.
Sept. ” ” Coast Sector, Nieuport
Bains.
Oct., Nov. ” ” Nieuport and St. Georges.
Nov., Dec., Jan., ” ” Opposite La Bassée.
Feb., 1918
1918
Mar., April ” ” Ervillers, Bucquoy.
May, June, July ” ” Bucquoy, Gommecourt,
Hébuterne.
Aug. Advanced through Miraumont, Riencourt,
Villers-au-Flos.
Sept. ” ” Havrincourt Wood to
Welsh Ridge.
Oct. ” ” Esnes, Beauvois, across
R. Selle.
Nov. ” ” Le Quesnoy, Mormal
Forest to Hautmont.
Nov. 11 Stood fast on line of Maubeuge—Avesnes
Road.
ILLUSTRATIONS
Facing page
MAJOR-GENERAL SIR WM. DOUGLAS, K.C.M.G., C.B.,
D.S.O. Frontispiece
MAJOR-GENERAL A. SOLLY-FLOOD, C.B., C.M.G.,
D.S.O. iv
CAPT. W. T. FORSHAW, V.C., 1/9TH BN. MANCHESTER
REGT. 46
LIEUT. A. V. SMITH, V.C., 1/5TH BN. EAST LANCS.
REGT. 57
PTE. W. MILLS, V.C., 1/10TH BN. MANCHESTER REGT. 116
SGT. E. SMITH, V.C., D.C.M., 1/5TH LANCS. FUS. 157
LC.-CORP. A. WILKINSON, V.C., 1/5TH BN.
MANCHESTER REGT. 187
LIEUT.-COL. P. V. HOLBERTON 131
THE DIVISIONAL COMMANDER AND BRIGADIERS 242
EGYPT AND SUEZ CANAL 18
GALLIPOLI: C. HELLES AND KRITHIA NULLAH SECTOR 19-29
C. HELLES AND GULLY RAVINE SECTOR 48-60
SINAI PENINSULA 76-83
COLOURED PLATE: DIVISIONAL FLASHES 84
BELGIUM: YPRES SECTOR 98-104
NIEUPORT SECTOR 105-108
FRANCE: LA BASSÉE SECTOR 114-118
THE GERMAN OFFENSIVE, MARCH 1918 130-131
GOMMECOURT—HÉBUTERNE SECTOR, APRIL-AUGUST
1918 142
THE BRITISH ADVANCE: MIRAUMONT—TRESCAULT 148-166
” ” THE HINDENBURG LINE 172
” ” ACROSS THE R. SELLE 182-186
” ” FORÊT DE MORMAL AND
HAUTMONT 192
MAPS
KEY MAP x
GALLIPOLI: CAPE HELLES 22
TRENCH MAP 34
FRANCE: THE GERMAN OFFENSIVE, 1918 128
THE BRITISH ADVANCE, 1918, FIRST STAGE 171
” ” ” FINAL STAGE 179
THE 42nd (EAST
LANCASHIRE) DIVISION
CHAPTER I
LANCASHIRE AND EGYPT
(August 1914—May 1915)
For a week or two there had been talk of war and of the likelihood
of England being involved. The prospects and possibilities formed an
interesting topic of conversation and speculation. We leant over the
sheer side of the precipice and caught glimpses of the black chasm
below, but few really doubted the soundness of the fence over which
we peered.
Warnings of disaster had been frequent—but disaster had always
been averted, and fair words had prevailed. For years we had been
living on the verge of national ruin through strikes of railway-men,
transport-workers, miners, or the spinners and weavers of
Lancashire, but at the last moment conciliation always won; there
was always room for compromise. Though civil war in Ireland
seemed imminent, it was comforting to reflect how much common
sense there was in the world. Besides, had it not been proved to
every one’s satisfaction that under modern conditions war between
great nations could not possibly last for more than a month or two,
as in that short period victor and vanquished would alike be reduced
to bankruptcy and impotence? Knowing this no Great Power would
be likely to commit suicide. We were living in the twentieth century,
and a great European war was an abstract conception, not
something that could actually occur.
In the closing days of July 1914 this complacency was giving way
to a very real dread. War might mean suicide even for the victor,
might be “unthinkable,” but it was in sight—plain, stark, menacing.
War such as other nations had known; not a war in which those who
had a taste for soldiering might take part while the rest of us could
read about it in the papers, feel proud of a success and depressed
by a disaster, and wonder whether sixpence would be added to the
income tax. The fantastic image that had thrilled us not altogether
unpleasantly—as children experience ecstatic shudders when
listening to tales of ogres and hobgoblins—was taking on an
appearance of grim reality. Could it after all be a grisly spectre and
not a mere bogey of turnip and white sheet? England began to
regret that the warnings of her greatest soldier had passed
unheeded.
A day or two later Germany flung down her challenge to
Christianity and Civilization, stripped herself of the cloak of decency
and stood revealed in stark brutishness; and on Tuesday, August 4,
1914, England took up the challenge and declared war. The decision
was apparently not expected by the German Staff. To them it was
rather a matter for exasperation than for apprehension. England had
her hands full at home, and her vast possessions would prove a
source of weakness. She had a small regular army, a force with high
traditions, well trained and well equipped for service on the frontiers
of India and other outposts of the Empire, containing a larger
proportion of officers and men with experience of actual fighting
than any other army of the Great Powers, yet so small in numbers
and so scattered over the face of the globe, that one can almost
sympathize with the German belief that the few thousand men who
could be spared from the duty of policing India, Egypt, South Africa,
and other possessions, might safely be regarded as negligible. She
had, too, a small, indifferently trained and equipped, unprofessional,
home-defence force, but even the British themselves did not take
the Territorials seriously.
As to the rest of the potential fighting material of the British Isles,
had it not been proved to the satisfaction of the Germans (who had
made a special study of such matters with the typical Teutonic
thoroughness which works so efficiently when applied to material
facts, and fails so lamentably when the human factor enters) that
the young manhood of the nation was mainly decadent, of poor
physique, weak-chested, half-educated, lacking in patriotic purpose,
with no thought of the morrow and no ideals? With the exception of
the few hundred thousands who had received some training in
physical drill and discipline in the Boys’ Brigade and its daughter-
organizations which teach discipline, self-respect, and esprit de
corps, or in the School Cadet Corps, all were utterly untrained, and
they hated discipline. England had clearly shown that she was too
selfish to submit to any form of compulsory service; too wrapped up
in the love of comfort, ease and luxury to do more than bribe fools
to die for her. It was a nation that had lost its soul. The military aid
she could give to France could be contemptuously brushed aside.
When France had been paralysed and the Channel ports secured,
the British mercantile marine could be sunk or scared off the seas,
and the British Empire brought to its knees.
Teutonic reasoning was wrong. The British character is too simple
or too complex for the Hun. It may be that no other nation brings so
much froth to the top as ours; that none extends such tolerance to
cranks, nor gives so much rope to little cliques of shrieking egoists,
nor shows such stolid indifference when the few, claiming to speak
on behalf of the nation, so egregiously misrepresent her. On August
5, 1914, it was seen that practically every man, woman and child
approved what the Government had done, and felt instinctively that
their country would have been shamed had there been a day’s
hesitation. England had found her soul, not lost it. A nation
supposed to consist largely of pleasure seekers, of lovers of
compromise, conciliation and tolerance, of comfort and luxury, had
decided that all it held most dear would be as dust and ashes if it
stood aside, a passive spectator of the agony of France and Belgium.
Practically without a dissentient voice the nation prepared to
sacrifice its all. Unhappily, the politicians, unaccustomed to realities,
were not ready to make the most of this spirit of sacrifice. Unable to
leave their grooves of finesse, intrigue, and opportunism, they knew
not how to appeal simply to the noblest instincts; so they talked of
“business as usual,” and attempted to cajole the nation into giving a
part when the whole was ready to be offered.
This is the story of the part played in the most Composition of
appalling of human tragedies by the East
Lancashire Territorial Division, which, on leaving the Division
England, was composed of the following units—

Cavalry: “A” Squadron, Duke of Lancaster’s Own Yeomanry—6


officers, 132 men.
R.F.A.: The 1st (Blackburn) and the 3rd (Bolton) East Lancashire
Brigades—55 officers, 1289 men.
R.E.: 1st and 2nd Field Companies and Signal Company—19
officers, 568 men.
Infantry: The 5th, 6th, 7th and 8th Battalions, the Lancashire
Fusiliers—120 officers, 3962 men.
The 4th and 5th Battalions, the East Lancashire Regiment—
60 officers, 1990 men.
The 5th, 6th, 7th, 8th, 9th, and 10th Battalions, the
Manchester Regiment—180 officers, 5966 men.
A.S.C.: Three Companies and the Transport and Supply Column
—16 officers, 276 men.
R.A.M.C.: Three Field Ambulances—30 officers, 665 men.
Total (including Divisional and Brigade Headquarters): 511
officers, 14,966 men.

The twelve battalions of infantry were brigaded as follows—


The Lancashire Fusiliers Brigade—the 5th, 6th, 7th, and 8th
Battalions, Lancashire Fusiliers.
The East Lancashire Brigade—the 4th and 5th Battalions, East
Lancs Regiment, and the 9th and 10th Battalions, Manchester
Regiment.
The Manchester Brigade—the 5th, 6th, 7th, and 8th Battalions,
Manchester Regiment.
The 5th L.F. was mainly composed of men from the Bury district,
the 6th from Rochdale, the 7th and 8th from Salford, the 4th E.
Lancs from Blackburn, the 5th from Burnley, the 5th Manchesters
from Wigan, the 6th and 7th from Manchester and its suburbs
(including a good proportion from the Cheshire suburbs), the 8th
from Ardwick and East Manchester, the 9th from Ashton-under-Lyne,
the 10th from Oldham.
The 1st R.F.A. Brigade (Blackburn) was composed of the following
batteries: the 4th (Blackburn), the 5th (Church), the 6th (Burnley).
The 3rd R.F.A. Brigade (Bolton) of the following: the 18th, 19th and
20th, all from Bolton and district.
Many of these units date back to 1859, when the Volunteer
movement came into being. For forty-one years the Volunteers were
an untried force, but in the year 1900 their offers of service in the
South African War were accepted, the infantry battalions providing
detachments which served with credit in that campaign. It was not
until 1907 that serious thought was given to the equipment and
organization of this fine body of patriotic men. Lord Haldane’s
Territorial Scheme, based on the model of the Regular Army, did
more than change the name from Volunteers to Territorials. Major-
General Douglas Haig, Director of Military Training at the War Office,
had charge of the scheme, and in bringing about this great change,
he gave evidence of the foresight and grasp of essentials which in
1918 enabled him to lead the armed strength of the Empire to
victory. The various batteries, battalions and corps, no longer
scattered and independent units, were organized and trained as
divisions, and the force was actually treated as a valuable and even
essential element in the system of national defence, with the result
that the Territorial Force soon reached a higher state of efficiency
than the Volunteers had ever been permitted to approach. The East
Lancashire Division had the reputation of being one of the smartest
and most efficient of the whole force.
On August 3 units in camp for their annual peace Mobilization
training were recalled, and the order to mobilize
the Division was received at 5.30 p.m. on the following day. Probably
few members of the Territorial Force had realized that their “calling-
up” notices had been ready from the day they joined; that month by
month the addresses on the envelopes were checked and altered
when necessary; that enough ball ammunition was stored at the
various headquarters to enable every man to march out with the full
complement of a fighting soldier, and that field dressings were
available for issue. It must be remembered that never before had
the Force been embodied, and that officers and men were civilians,
few of whom had ever regarded mobilization as other than a remote
possibility quite outside the range of practical politics. Yet the
absence of confusion was remarkable, as all ranks threw themselves
into their new parts with zest, making the best of unusual conditions
and treating discomfort as a jest. The men were quartered in drill-
halls or schools within easy reach of their Headquarters. Major-
General Douglas, commanding the Division, with his General Staff
Officer, Lieut.-Colonel A. W. Tufnell, was daily at the Divisional
Headquarters in Manchester, or at the Headquarters of units,
supervising the mobilization and arrangements. These have been
described as “hectic days.” Improved though the organization was as
compared with that of the Volunteers, it was anything but complete.
Animals and vehicles for transport, harness, and an infinite variety of
requisites had to be procured by free purchase or by
commandeering in great haste. This was the weakest part of the
scheme, and though much ingenuity was displayed by officers
unaccustomed to this sort of thing, the waste was great. To such
shifts were they reduced that street watering-carts were bought
from Urban District Councils, and actually taken to Egypt. Among the
weird varieties of carts thus acquired one of the best remembered is
the “Black and Green” van which did duty as a Medical Officer’s
vehicle, and was last seen bleached by the sun, but with the original
lettering still traceable under the service grey, at Gabari Docks,
Alexandria in February 1917. Nothing could better illustrate the
inability of a large and patriotic section of the public to grasp the
significance of events than the expectation freely expressed by
vendors that their horses or carts would be returned to them in the
course of a few weeks. In some cases the drivers of requisitioned
animals joined the Territorial unit in order to remain with their
horses.
On August 10 Lord Kitchener invited the Territorial Force to
volunteer for foreign service. By August 12 the three Infantry
Brigades had accepted the invitation, and within a few days ninety
per cent. of the East Lancashires eagerly seized the opportunity.
England saw with pride the keenness of the Territorials to meet the
enemy, and knew that her sons were true to the breed. For more
than fifty years she had treated her citizen-army as something that
must not be taken too seriously, but that is England’s way. The
response was magnificent, but it was expected, for the nation never
doubted that they would answer the call. It was no small gift they
offered. The most powerful army the world had ever seen was
moving forward victoriously towards Paris, remorseless and
apparently irresistible; and the Territorials offered their bodies for
death and mutilation, and gave up parents, wives, children, homes,
prospects, and all they held most dear. At a later period such
sacrifice was demanded as the nation’s right, but in August 1914 a
lead had to be given, an example set. Old volunteers were not
content to look on while the younger generation fought and
suffered. Daily a stream of old members, N.C.O.s and men, many in
the autumn of their lives, besieged the Headquarters of their old
corps and clamoured to be allowed to join up, lying cheerfully and
brazenly in respect of their age. Many gained their object; more
were almost broken-hearted by their rejection. The example set in
those dark days was a stimulus and incentive to recruiting all over
the country, and especially so in the great towns of Lancashire,
where the “Pals” battalions were soon to be raised. It was the
vindication of the Volunteer. “Defence, not Defiance,” had been their
motto, but who among the prescient founders and bulwarks of the
movement could ever have conceived the idea of the glorious rôle to
be filled by the corps they had helped to raise—of the old Volunteer
units from every county and city, at full strength, fighting and laying
down their lives in Belgium, France, Egypt, Gallipoli, Palestine and
Greece, and taking an inspiring part in the greatest of all crusades
against the Turk?
Until August 20 officers and men remained within easy reach of
their Headquarters. The Division was then moved into camps in the
neighbourhoods of Bolton, Bury and Rochdale, and anxiously it
awaited the summons. Another fortnight passed, and the rumour
that Egypt was to be the destination began to gain ground. Rumour
was, however, at this time a discredited jade, fit subject for scorn,
for was she not responsible for the passage through England and
Scotland of myriads of Russian soldiers, the ice and snow of
Archangel still clinging to their boots and beards, who had been
seen by thousands of British optimists at every railway junction in
the land? But in the training camps of East Lancashire she was
restored to public favour when a telegram, dated September 5, was
received by the Divisional Commander from Lord Kitchener—

“Inform the Division from me that I hope that they will


push on hard with their training in Egypt, as, before they are
ready, there will be plenty of troops from India to garrison
Egypt, and I hope they will be one of the first of the
Territorial Forces to join our Army on the Continent. All will
depend on their fitness for service against the enemy in the
Field.—Kitchener.”

General Douglas spoke for every man in the Division when he


replied: “All ranks much gratified to receive your message. They are
animated with keen desire to fit themselves to join our forces on the
Continent.”
On the 9th September the Division entrained for Southampton,
about forty trains being required to convey men, horses, guns, and
all the material of war; and on the 10th 15,500 Lancashire men, with
about a thousand officers and men of the Hertfordshire and City of
Westminster Yeomanry, embarked upon the great adventure, the
first Territorial Division to volunteer for foreign service, and the first

You might also like