Tải bản đầy đủ (.pdf) (938 trang)

Professional java for web applications nicholas s williams(www ebook dl com)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.34 MB, 938 trang )


ffirs.indd 6

11-02-2014 09:02:59


Professional

Java® for Web Applications
Nicholas S. Williams

ffirs.indd 1

19-02-2014 12:20:41


Professional Java® for Web Applications
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-65646-4
ISBN: 978-1-118-65651-8 (ebk)
ISBN: 978-1-118-90931-7 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,


electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)
748-6008, or online at />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
­promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work
is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
­services. If professional assistance is required, the services of a competent professional person should be sought. Neither
the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Web site may provide or recommendations it may make. Further,
readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this
work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with
­standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to
media such as a CD or DVD that is not included in the version you purchased, you may download this material at
. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2013958292
Trademarks: Wiley, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or
­registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may
not be used without written permission. Java is a registered trademark of Oracle America, Inc. All other trademarks are
the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned
in this book.

ffirs.indd 2


24-02-2014 12:36:52


About the Author

Nick Williams  is a Software Engineer for UL Workplace Health and Safety
in Franklin, Tennessee. A computer science graduate from Belmont University,
he has been active in commercial and open source software projects for more
than 9 years. He is the founder of DNSCrawler.com, a site for free DNS and
IP troubleshooting tools, and NWTS Java Code, an open source community
that specializes in obscure Java libraries that meet niche needs. In 2010, the
Nashville Technology Council named him the Software Engineer of the Year
for Middle Tennessee. Nick is a committer for Apache Logging (including
Log4j) and Jackson Data Processor JSR 310 Data Types. He has also ­contributed new features to
Apache Tomcat 8.0, Spring Framework 4.0, Spring Security 3.2, Spring Data Commons 1.6, Spring
Data JPA 1.4, and JBoss Logging 3.2; serves as a contributor on several other projects, including
OpenJDK; and is a member of the Java Community Process (JCP).

Nick currently lives in Tennessee with his wife Allison. You can find him on Twitter @Java_Nick.

About the Technical Editors

Jake Radakovich  joined UL Workplace Health and Safety in 2009, and currently serves as

Software Developer on the Occupational Health Manager product. Prior to that, he was a
research assistant at Middle Tennessee State University working on AlgoTutor, a web-based
algorithm development tutoring system. He holds a BS in Computer Science and Mathematics
from Middle Tennessee State University. You can follow Jake on Twitter @JakeRadakovich.
Manuel Jordan Elera  is an autodidactic developer and researcher who enjoys learning new

technologies for his own experiments and creating new integrations. He won the 2010 Springy
Award and was a Community Champion and Spring Champion in 2013. In his little free time,
he reads the Bible and composes music on his guitar. Manuel is a Senior Member in the Spring
Community Forums known as dr_pompeii. You can read about him and contact him through his
blog and you can follow him on his Twitter account, @dr_pompeii.

ffirs.indd 3

24-02-2014 12:36:53


Credits
Acquisitions Editor

Marketing Manager

Mary James

Ashley Zurcher

Project Editor

Business Manager

Maureen Spears Tullis

Amy Knies

Technical Editors


Vice President and Executive Group
Publisher

Michael Jordan Elera
Jake Radakovich

Richard Swadley

Technical Proofreader

Associate Publisher

Jonathan Giles

Jim Minatel

Senior Production Editor

Project Coordinator, Cover

Kathleen Wisor

Todd Klemme

Copy Editor

Proofreaders

Apostrophe Editing Services


Nancy Carrasco
Josh Chase, Word One

Editorial Manager

Mary Beth Wakefield

Indexer

Robert Swanson
Freelancer Editorial Manager

Rosemarie Graham

Cover Designer

Wiley
Associate Director of Marketing

David Mayhew

Cover Image

iStockphoto.com/ElementalImaging

ffirs.indd 4

24-02-2014 12:36:53



Acknowledgments

Thanks to...

My wife Allison, whose unwavering support and persistent reminders about deadlines during
this stressful year made this book possible.
My parents and siblings, who told me that I could do anything I put my mind to.
Drs. Joyce Blair Crowell and William Hooper, whose dedicated instruction and mentoring
made my career possible.
Dr. Sarah Ann Stewart, who believed in me when I thought surely calculus and proofs spelled
doom for my education.
Mrs. Lockhart, who inspired me to write.
Jay, for introducing me to Mary, and to Mary and Maureen for making this book a reality.
Jake, for being absurd. Oh, and for agreeing to be my technical editor.

ffirs.indd 5

24-02-2014 12:36:53


ffirs.indd 6

24-02-2014 12:36:53


Contents

Introduction

xxiii


Part I: Creating Enterprise Applications
Chapter 1: Introducing Java Platform, Enterprise Edition 3

A Timeline of Java Platforms
In the Beginning
The Birth of Enterprise Java
Java SE and Java EE Evolving Together
Understanding the Most Recent Platform Features
A Continuing Evolution

Understanding the Basic Web Application Structure
Servlets, Filters, Listeners, and JSPs
Directory Structure and WAR Files
The Deployment Descriptor
Class Loader Architecture
Enterprise Archives

3
4
5
6
9
13

13
13
14
15
16

17

Summary18
Chapter 2: Using Web Containers

Choosing a Web Container

19

19

Apache Tomcat
20
GlassFish21
JBoss and WildFly
22
Other Containers and Application Servers
22
Why You’ll Use Tomcat in This Book
23

Installing Tomcat on Your Machine
Installing as a Windows Service
Installing as a Command-Line Application
Configuring a Custom JSP Compiler

Deploying and Undeploying Applications in Tomcat
Performing a Manual Deploy and Undeploy
Using the Tomcat Manager


ftoc.indd 7

23
24
24
26

27
28
28

11-02-2014 08:39:54


CONTENTS

Debugging Tomcat from Your IDE
Using IntelliJ IDEA
Using Eclipse

30
30
35

Summary39
Chapter 3: Writing Your First Servlet

Creating a Servlet Class
What to Extend
Using the Initializer and Destroyer


41

42
42
45

Configuring a Servlet for Deployment

46

Adding the Servlet to the Descriptor
Mapping the Servlet to a URL
Running and Debugging Your Servlet

46
47
49

Understanding doGet(), doPost(), and Other Methods
What Should Happen during the service Method Execution?
Using HttpServletRequest
Using HttpServletResponse

Using Parameters and Accepting Form Submissions
Configuring your Application Using Init Parameters
Using Context Init Parameters
Using Servlet Init Parameters

Uploading Files from a Form

Introducing the Customer Support Project
Configuring the Servlet for File Uploads
Accepting a File Upload

Making Your Application Safe for Multithreading
Understanding Requests, Threads, and Method Execution
Protecting Shared Resources

51
51
52
55

56
61
61
62

64
65
65
68

69
69
70

Summary71
Chapter 4: Using JSPs to Display Content


73


Is Easier Than output.println(“
”)

74

Why JSPs Are Better
What Happens to a JSP at Run Time

Creating Your First JSP
Understanding the File Structure
Directives, Declarations, Scriptlets, and Expressions
Commenting Your Code
Adding Imports to Your JSP

75
76

78
78
79
81
82

viii

ftoc.indd 8


11-02-2014 08:39:54


CONTENTS

Using Directives
Using the <jsp> Tag

Using Java within a JSP (and Why You Shouldn’t!)
Using the Implicit Variables in a JSP
Why You Shouldn’t Use Java in a JSP

Combining Servlets and JSPs
Configuring JSP Properties in the Deployment Descriptor
Forwarding a Request from a Servlet to a JSP

83
86

88
88
93

94
94
97

A Note about JSP Documents (JSPX)
102
Summary104

Chapter 5: Maintaining State Using Sessions

Understanding Why Sessions Are Necessary
Maintaining State
Remembering Users
Enabling Application Workflow

Using Session Cookies and URL Rewriting
Understanding the Session Cookie
Session IDs in the URL
Session Vulnerabilities

Storing Data in a Session
Configuring Sessions in the Deployment Descriptor
Storing and Retrieving Data
Removing Data
Storing More Complex Data in Sessions

Applying Sessions Usefully
Adding Login to the Customer Support Application
Detecting Changes to Sessions Using Listeners
Maintaining a List of Active Sessions

105

106
106
107
107


107
108
110
112

116
116
119
123
125

129
129
133
135

Clustering an Application That Uses Sessions

139

Using Session IDs in a Cluster
Understand Session Replication and Failover

139
141

Summary142
Chapter 6: Using the Expression Language in JSPs

Understanding Expression Language

What It’s For
Understanding the Base Syntax
Placing EL Expressions

Writing with the EL Syntax

143

144
144
145
146

147

ix

ftoc.indd 9

11-02-2014 08:39:54


CONTENTS

Reserved Keywords
148
Operator Precedence
148
Object Properties and Methods
154

EL Functions
155
Static Field and Method Access
156
Enums157
Lambda Expressions
157
Collections158

Using Scoped Variables in EL Expressions
Using the Implicit EL Scope
Using the Implicit EL Variables

160
161
165

Accessing Collections with the Stream API

167

Understanding Intermediate Operations
Using Terminal Operations
Putting the Stream API to Use

168
170
171

Replacing Java Code with Expression Language

172
Summary175
Chapter 7: Using the Java Standard Tag Library

Introducing JSP Tags and the JSTL
Working with Tags

Using the Core Tag Library (C Namespace)

177

178
178

182

<c:out>182
<c:url>183
<c:if>184
<c:choose>, <c:when>, and <c:otherwise>
185
<c:forEach>186
<c:forTokens>187
<c:redirect>188
<c:import>188
<c:set> and <c:remove>
189
Putting Core Library Tags to Use
190


Using the Internationalization and Formatting
  Tag Library (FMT Namespace)

193

Internationalization and Localization Components
193
<fmt:message>194
<fmt:setLocale>196
<fmt:bundle> and <fmt:setBundle>
196
<fmt:requestEncoding>197
<fmt:timeZone> and <fmt:setTimeZone>
197
<fmt:formatDate> and <fmt:parseDate>
198
<fmt:formatNumber> and <fmt:parseNumber>
199
x

ftoc.indd 10

11-02-2014 08:39:54


CONTENTS

Putting i18n and Formatting Library Tags to Use

200


Using the Database Access Tag
  Library (SQL Namespace)
203
Using the XML Processing Tag
  Library (X Namespace)
205
Replacing Java Code with JSP Tags
205
Summary208
Chapter 8: Writing Custom Tag and Function Libraries

209

Understanding TLDs, Tag Files, and Tag Handlers

210

Reading the Java Standard Tag Library TLD
Comparing JSP Directives and Tag File Directives

211
217

Creating Your First Tag File to Serve
  as an HTML Template
219
Creating a More Useful Date Formatting
  Tag Handler
221

Creating an EL Function to Abbreviate Strings
226
Replacing Java Code with Custom JSP Tags
227
Summary232
Chapter 9: Improving Your Application Using Filters

233

Understanding the Purpose of Filters

234

Logging Filters
Authentication Filters
Compression and Encryption Filters
Error Handling Filters

234
234
234
235

Creating, Declaring, and Mapping Filters
Understanding the Filter Chain
Mapping to URL Patterns and Servlet Names
Mapping to Different Request Dispatcher Types
Using the Deployment Descriptor
Using Annotations
Using Programmatic Configuration


Ordering Your Filters Properly
URL Pattern Mapping versus Servlet Name Mapping
Exploring Filter Order with a Simple Example
Using Filters with Asynchronous Request Handling

Investigating Practical Uses for Filters
Adding a Simple Logging Filter
Compressing Response Content Using a Filter

235
235
236
236
237
238
238

239
239
241
243

247
248
249

Simplifying Authentication with a Filter
254
Summary255

xi

ftoc.indd 11

11-02-2014 08:39:54


CONTENTS

Chapter 10: Making Your Application Interactive
with WebSockets

Evolution: From Ajax to WebSockets
Problem: Getting New Data from the
  Server to the Browser
Solution 1: Frequent Polling
Solution 2: Long Polling
Solution 3: Chunked Encoding
Solution 4: Applets and Adobe Flash
WebSockets: The Solution Nobody Knew Kind
  of Already Existed

Understanding the WebSocket APIs
HTML5 (JavaScript) Client API
Java WebSocket APIs

257

258
259

259
260
262
263
264

268
268
270

Creating Multiplayer Games with WebSockets

273

Implementing the Basic Tic-Tac-Toe Algorithm
Creating the Server Endpoint
Writing the JavaScript Game Console
Playing WebSocket Tic-Tac-Toe

274
274
278
283

Using WebSockets to Communicate in a Cluster
Simulating a Simple Cluster Using Two Servlet Instances
Transmitting and Receiving Binary Messages
Testing the Simulated Cluster Application

Adding “Chat with Support” to the Customer

  Support Application
Using Encoders and Decoders to Translate Messages
Creating the Chat Server Endpoint
Writing the JavaScript Chat Application

284
284
286
287

288
289
291
294

Summary296
Chapter 11: Using Logging to Monitor Your Application 297

Understanding the Concepts of Logging
Why You Should Log
What Content You Might Want to See in Logs
How Logs Are Written

Using Logging Levels and Categories
Why Are There Different Logging Levels?
Logging Levels Defined
How Logging Categories Work
How Log Sifting Works

Choosing a Logging Framework

API versus Implementation

298
298
299
301

303
303
303
304
305

305
305

xii

ftoc.indd 12

11-02-2014 08:39:54


CONTENTS

Performance306
A Quick Look at Apache Commons Logging and SLF4J
307
Introducing Log4j 2
307


Integrating Logging into Your Application
Creating the Log4j 2 Configuration Files
Utilizing Fish Tagging with a Web Filter
Writing Logging Statements in Java Code
Using the Log Tag Library in JSPs
Logging in the Customer Support Application

312
313
316
317
319
319

Summary320
Part II: Adding Spring Framework Into the Mix
Chapter 12: Introducing Spring Framework

What Is Spring Framework?
Inversion of Control and Dependency Injection
Aspect-oriented Programming
Data Access and Transaction Management
Application Messaging
Model-View-Controller Pattern for Web Applications

Why Spring Framework?
Logical Code Groupings
Multiple User Interfaces Utilizing One Code Base


Understanding Application Contexts
Bootstrapping Spring Framework
Using the Deployment Descriptor to Bootstrap Spring
Programmatically Bootstrapping Spring in an Initializer

Configuring Spring Framework
Creating an XML Configuration
Creating a Hybrid Configuration
Configuring Spring with Java Using @Configuration

Utilizing Bean Definition Profiles
Understanding How Profiles Work
Considering Antipatterns and Security Concerns

323

324
325
325
325
326
326

326
326
327

327
329
330

332

336
338
340
345

349
350
352

Summary353
Chapter 13: Replacing Your Servlets with Controllers

Understanding @RequestMapping
Using @RequestMapping Attributes to Narrow
  Request Matching
Specifying Controller Method Parameters
Selecting Valid Return Types for Controller Methods

355

356
356
360
368
xiii

ftoc.indd 13


11-02-2014 08:39:54


CONTENTS

Using Spring Framework’s Model and View Pattern

370

Using Explicit Views and View Names
Using Implicit Views with Model Attributes
Returning Response Entities

371
373
375

Making Your Life Easier with Form Objects

380

Adding the Form Object to Your Model
Using the Spring Framework <form> Tags
Obtaining Submitted Form Data

381
381
383

Updating the Customer Support Application


384

Enabling Multipart Support
Converting Servlets to Spring MVC Controllers
Creating a Custom Downloading View

384
385
386

Summary387
Chapter 14: Using Services and Repositories to Support
Your Controllers

389

Understanding Model-View-Controller Plus Controller-ServiceRepository390
Recognizing Different Types of Program Logic
Repositories Provide Persistence Logic
Services Provide Business Logic
Controllers Provide User Interface Logic

Using the Root Application Context
  Instead of a Web Application Context
Reusing the Root Application Context for Multiple
  User Interfaces
Moving Your Business Logic from
  Controllers to Services
Using Repositories for Data Storage


Improving Services with Asynchronous
  and Scheduled Execution
Understanding Executors and Schedulers
Configuring a Scheduler and Asynchronous Support
Creating and Using @Async Methods
Creating and Using @Scheduled Methods

Applying Logic Layer Separation to WebSockets
Adding Container-Managed Objects to the
  Spring Application Context
Using the Spring WebSocket Configurator
Remember: A WebSocket Is Just Another
  Interface for Business Logic

391
392
392
393

394
394
396
399

404
404
405
407
408


409
409
411
412

Summary416
xiv

ftoc.indd 14

11-02-2014 08:39:54


CONTENTS

Chapter 15: Internationalizing Your Application with
Spring Framework i18n

Why Do You Need Spring Framework i18n?
Making Internationalization Easier
Localizing Error Messages Directly

Using the Basic Internationalization
  and Localization APIs
Understanding Resource Bundles
  and Message Formats
Message Sources to the Rescue
Using Message Sources to Internationalize JSPs


Configuring Internationalization
  in Spring Framework
Creating a Message Source
Understanding Locale Resolvers
Using a Handler Interceptor to Change Locales
Providing a User Profile Locale Setting
Including Time Zone Support
Understanding How Themes Can Improve
 Internationalization

Internationalizing Your Code
Using the <spring:message> Tag
Handling Application Errors Cleanly
Updating the Customer Support Application
Using the Message Source Directly

417

418
418
418

419
419
421
422

424
424
425

427
428
429
429

430
431
433
436
437

Summary440
Chapter 16: Using JSR 349, Spring Framework, and
Hibernate Validator for Bean Validation

What Is Bean Validation?
Why Hibernate Validator?
Understanding the Annotation Metadata Model
Using Bean Validation with Spring Framework

Configuring Validation in the Spring
  Framework Container
Configuring the Spring Validator Bean
Setting Up Error Code Localization
Using a Method Validation Bean Post-Processor
Making Spring MVC Use the Same Validation Beans

Adding Constraint Validation Annotations
  to Your Beans


441

442
444
444
445

445
446
448
449
450

450

xv

ftoc.indd 15

11-02-2014 08:39:54


CONTENTS

Understanding the Built-in Constraint Annotations
Understanding Common Constraint Attributes
Putting Constraints to Use
Using @Valid for Recursive Validation
Using Validation Groups
Checking Constraint Legality at Compile-Time


451
452
452
454
455
457

Configuring Spring Beans for Method Validation

458

Annotating Interfaces, Not Implementations
Using Constraints and Recursive Validation
  on Method Parameters
Validating Method Return Values
Indicating That a Class Is Eligible for Method Validation
Using Parameter Validation in Spring MVC Controllers
Displaying Validation Errors to the User

Writing Your Own Validation Constraints
Inheriting Other Constraints in a Custom Constraint
Creating a Constraint Validator
Understanding the Constraint Validator Life Cycle

458
459
459
460
462

463

466
466
467
469

Integrating Validation in the Customer
  Support Application
470
Summary472
Chapter 17: Creating RESTful and SOAP Web Services

Understanding Web Services
In the Beginning There Was SOAP
RESTful Web Services Provide a Simpler Approach

Configuring RESTful Web Services
  with Spring MVC
Segregating Controllers with Stereotype Annotations
Creating Separate Web and REST Application Contexts
Handling Error Conditions in RESTful Web Services
Mapping RESTful Requests to Controller Methods
Improving Discovery with an Index Endpoint

473

474
475
476


484
484
485
488
491
495

Testing Your Web Service Endpoints

496

Choosing a Testing Tool
Making Requests to Your Web Service

497
497

Using Spring Web Services for SOAP

500

Writing Your Contract-First XSD and WSDL
Adding the SOAP Dispatcher Servlet Configuration
Creating a SOAP Endpoint

501
503
504


Summary508

xvi

ftoc.indd 16

11-02-2014 08:39:55


CONTENTS

Chapter 18: Using Messaging and Clustering for
Flexibility and Reliability

Recognizing When You Need Messaging
  and Clustering
What Is Application Messaging?
What Is Clustering?
How Do Messaging and Clustering Work Together?

Adding Messaging Support to your Application
Creating Application Events
Subscribing to Application Events
Publishing Application Events

Making your Messaging Distributable
  Across a Cluster
Updating Your Events to Support Distribution
Creating and Configuring a Custom Event Multicaster
Using WebSockets to Send and Receive Events

Discovering Nodes with Multicast Packets
Simulating a Cluster with Multiple Deployments

Distributing Events with AMQP
Configuring an AMQP Broker
Creating an AMQP Multicaster
Running the AMQP-Enabled Application

509

510
510
513
517

520
520
522
523

525
526
527
529
531
533

534
536
537

539

Summary540
Part III: Persisting Data with JPA and Hibernate ORM
Chapter 19: Introducing Java Persistence API and
Hibernate ORM

What Is Data Persistence?
Flat-File Entity Storage
Structured File Storage
Relational Database Systems
Object-Oriented Databases
Schema-less Database Systems

What Is an Object-Relational Mapper?
Understanding the Problem of Persisting Entities
O/RMs Make Entity Persistence Easier
JPA Provides a Standard O/RM API
Why Hibernate ORM?

A Brief Look at Hibernate ORM
Using Hibernate Mapping Files

543

543
544
544
545
546

546

547
547
549
550
552

552
552
xvii

ftoc.indd 17

11-02-2014 08:39:55


CONTENTS

Understanding the Session API
Getting a Session from the SessionFactory
Creating a SessionFactory with Spring Framework

Preparing a Relational Database
Installing MySQL and MySQL Workbench
Installing the MySQL JDBC Driver
Creating a Connection Resource in Tomcat

554
556

557

559
559
562
563

A Note About Maven Dependencies
564
Summary564
Chapter 20: Mapping Entities to Tables with
JPA Annotations

Getting Started with Simple Entities
Marking an Entity and Mapping It to a Table
Indicating How JPA Uses Entity Fields
Mapping Surrogate Keys
Using Basic Data Types
Specifying Column Names and Other Details

565

566
567
569
570
576
579

Creating and Using a Persistence Unit


581

Designing the Database Tables
Understanding Persistence Unit Scope
Creating the Persistence Configuration
Using the Persistence API

581
583
584
586

Mapping Complex Data Types
Using Enums as Entity Properties
Understanding How JPA Handles Dates and Times
Mapping Large Properties to CLOBs and BLOBs

590
590
592
594

Summary596
Chapter 21: Using JPA in Spring Framework Repositories 597

Using Spring Repositories and Transactions
Understanding Transaction Scope
Using Threads for Transactions and Entity Managers
Taking Advantage of Exception Translation


Configuring Persistence in Spring Framework
Looking Up a Data Source
Creating a Persistence Unit in Code
Setting Up Transaction Management

Creating and Using JPA Repositories
Injecting the Persistence Unit
Implementing Standard CRUD Operations

598
598
599
601

602
602
603
607

610
610
611

xviii

ftoc.indd 18

11-02-2014 08:39:55



CONTENTS

Creating a Base Repository for All Your Entities
Demarking Transaction Boundaries in Your Services
Using the Transactional Service Methods

Converting Data with DTOs and Entities
Creating Entities for the Customer Support Application
Securing User Passwords with BCrypt
Transferring Data to Entities in Your Services

613
618
622

624
624
628
630

Summary632
Chapter 22: Eliminating Boilerplate Repositories
with Spring Data JPA

Understanding Spring Data’s
  Unified Data Access
Avoiding Duplication of Code
Using the Stock Repository Interfaces
Creating Query Methods for Finding Entities

Providing Custom Method Implementations

Configuring and Creating Spring
  Data JPA Repositories

633

634
634
638
639
642

646

Enabling Repository Auto-Generation
Writing and Using Spring Data JPA Interfaces

646
654

Refactoring the Customer Support Application

656

Converting the Existing Repositories
Adding Comments to Support Tickets

656
657


Summary661
Chapter 23: Searching for Data with JPA
and Hibernate Search

An Introduction to Searching

663

664

Understanding the Importance of Indexes
Taking Three Different Approaches

664
666

Using Advanced Criteria to Locate Objects

666

Creating Complex Criteria Queries
Using OR in Your Queries
Creating Useful Indexes to Improve Performance

Taking Advantage of Full-Text Indexes with JPA
Creating Full-Text Indexes in MySQL Tables
Creating and Using a Searchable Repository
Making Full-Text Searching Portable


Indexing Any Data with Apache Lucene
  and Hibernate Search

667
674
676

676
677
678
684

684

xix

ftoc.indd 19

11-02-2014 08:39:55


CONTENTS

Understanding Lucene Full-Text Indexing
Annotating Entities with Indexing Metadata
Using Hibernate Search with JPA

685
686
688


Summary692
Chapter 24: C
 reating Advanced Mappings
and Custom Data Types

What’s Left?
Converting Nonstandard Data Types
Understanding Attribute Converters
Understanding the Conversion Annotations
Creating and Using Attribute Converters

Embedding POJOs Within Entities
Indicating That a Type Is Embeddable
Marking a Property as Embedded
Overriding Embeddable Column Names

Defining Relationships Between Entities
Understanding One-to-One Relationships
Using One-to-Many and Many-to-One Relationships
Creating Many-to-Many Relationships

Addressing Other Common Situations
Versioning Entities with Revisions and Timestamps
Defining Abstract Entities with Common Properties
Mapping Basic and Embedded Collections
Persisting a Map of Key-Value Pairs
Storing an Entity in Multiple Tables

Creating Programmatic Triggers


693

694
695
695
696
698

699
699
700
702

703
703
705
708

709
709
710
712
715
716

717

Acting before and after CRUD Operations
Using Entity Listeners


717
719

Refining the Customer Support Application

720

Mapping a Collection of Attachments
Lazy Loading Simple Properties with Load Time Weaving

721
723

Summary725
Part IV: Securing Your Application with Spring Security
Chapter 25: Introducing Spring Security

What Is Authentication?
Integrating Authentication
Understanding Authorization

Why Spring Security?

729

729
730
740


743

xx

ftoc.indd 20

11-02-2014 08:39:55


CONTENTS

Understanding the Spring Security Foundation
Using Spring Security’s Authorization Services
Configuring Spring Security

744
745
745

Summary746
Chapter 26: Authenticating Users with Spring Security

Choosing and Configuring an
  Authentication Provider
Configuring a User Details Provider
Working with LDAP and Active Directory Providers
Authenticating with OpenID
Remembering Users
Exploring Other Authentication Providers


Writing Your Own Authentication Provider
Bootstrapping in the Correct Order
Creating and Configuring a Provider
Mitigating Cross-Site Request Forgery Attacks

747

748
748
759
762
765
766

766
767
769
775

Summary778
Chapter 27: Using Authorization Tags and Annotations 779

Authorizing by Declaration
Checking Permissions in Method Code
Employing URL Security
Using Annotations to Declare Permissions
Defining Method Pointcut Rules

Understanding Authorization Decisions
Using Access Decision Voters

Using Access Decision Managers

Creating Access Control Lists for Object Security
Understanding Spring Security ACLs
Configuring Access Control Lists
Populating ACLs for Your Entities

Adding Authorization to Customer Support
Switching to Custom User Details
Securing Your Service Methods
Using Spring Security’s Tag Library

780
780
783
786
794

794
795
796

798
798
800
803

804
804
808

813

Summary814
Chapter 28: Securing RESTful Web Services with OAuth

Understanding Web Service Security
Comparing Web GUI and Web Service Security

815

816
816
xxi

ftoc.indd 21

11-02-2014 08:39:55


CONTENTS

Choosing an Authentication Mechanism

Introducing OAuth
Understanding the Key Players
The Beginning: OAuth 1.0
The Standard: OAuth 1.0a
The Evolution: OAuth 2.0

Using Spring Security OAuth

Creating on OAuth 2.0 Provider
Creating an OAuth 2.0 Client

817

818
819
819
820
826

833
833
838

Finishing the Customer Support Application

840

Generating Request Nonces and Signatures
Implementing Client Services
Implementing Nonce Services
Implementing Token Services
Customizing the Resource Server Filter
Reconfiguring Spring Security

840
842
845
847

850
852

Creating an OAuth Client Application
Customizing the REST Template
Configuring the Spring Security OAuth Client
Using the REST Template
Testing the Provider and Client Together

856
857
858
861
861

Summary862
Index

865

xxii

ftoc.indd 22

11-02-2014 08:39:55


Introduction

Though many don’t realize it, most people use Java every day.  It’s all around you — ​it’s


in your TV, in your Blu-ray player, and on your computer; some popular smart phones run a Javabased operating system; and it powers many of the websites you use every day. When you think of
Java, you may naturally picture browser applets or desktop applications with user interfaces that
don’t match other applications on the operating system. You may even think of that annoying system tray notification that tells you to update Java (seemingly) constantly.
But Java is much more than just these daily, visible reminders you may be exposed to. Java is a
­powerful language, but much of its capability lies in the power of the platform. Although the Java
SE platform provides indispensable tools for creating console, desktop, and browser applications, the
Java EE platform extends this platform significantly to help you create rich, powerful web applications. This book covers these tools and shows you how to create modern and useful enterprise Java
web applications.

Who This Book Is For
This book is for software developers and engineers who already have a proficient knowledge in the
Java language and the Java Platform, Standard Edition (Java SE). It is a self-guided, self-study book
that existing Java developers can use to expand their Java knowledge and grow their skillset from
applets or console or desktop applications to enterprise web applications. You can read this book
from start to finish to cover all the topics in order, or you can pick and choose topics that interest
you and use this book more as a reference. Although some chapters occasionally refer to examples
from previous chapters, an effort was made to make each chapter as self-sustaining as possible. The
examples are all available for download from wrox.com, which should help you when an example
relies on another example from a previous chapter.
This book can also be useful for developers with existing Java Platform, Enterprise Edition (Java
EE) experience who want to refresh their skills or learn about new features in the latest Java EE
version. Software architects might also find this book useful because it covers several web software
development concepts and patterns in addition to specific tools and platform components. This book
could help architects apply new ideas to their teams’ projects and processes.
If you’re a manager of a software development team, you may also find this book helpful.
Undoubtedly you strive every day to communicate effectively with the developers and engineers that
you oversee. By reading this book, you can expand your knowledgebase, understand the tools your
developers use to more successfully communicate, and make recommendations to your team to solve
certain problems. After reading this book, you may also decide to purchase several copies for your

team to improve their skillsets and apply the concepts within your projects.
Finally, teachers and students can apply this book to a classroom environment. Used as a textbook,
it can be invaluable for 300 and 400 level courses to instruct students in real-world skills that can
help them succeed in the workplace beyond graduation.

flast.indd 23

24-02-2014 12:19:05


×