13
Professional Java™ Development with the Spring Framework Rod Johnson Juergen Hoeller Alef Arendsen Thomas Risberg Colin Sampaleanu WILEY Wiley Publishing, Inc.

Professional Java™ Development with the Spring Framework · Chapter 12: Web MVC Framework 423 A Simple Example 423 General Architecture 425 Web MVC Concepts 426 Generic Web MVC

Embed Size (px)

Citation preview

Professional Java™ Developmentwith the Spring Framework

Rod JohnsonJuergen HoellerAlef Arendsen

Thomas RisbergColin Sampaleanu

WILEY

Wiley Publishing, Inc.

Contents

Acknowledgments ixIntroduction xxiii

Chapter 1: Introducing the Spring Framework 1

Why Spring? 1Problems with the Traditional Approach to J2EE 1Lightweight Frameworks 3Enter Spring 5

Spring's Values 6Spring in Context 8

Technologies 8Techniques 18Relationship to Other Frameworks 19

Architecting Applications with Spring 2 1The Big Picture 21Persistence and Integration 23Business Service Objects 27Presentation 27

The Future 29Release Schedule 29The Evolution of Java and J2EE 29Technology Currents 31Standards and Open Source 31

The Spring Project and Community 32History 32Module Summary 33Supported Environments 37

Summary 37

Chapter 2: The Bean Factory and Application Context 3£>

Inversion of Control and Dependency Injection 40Different Forms of Dependency Injection 43Deciding Between Setter Injection and Constructor Injection 45

The Container ' 47The Bean Factory 47The Application Context 48Starting the Container 50

Contents

Using Beans from the Factory 52XML Bean Configuration 53The Basic Bean Definition 53Specifying Bean Dependencies 56Managing the Bean Lifecycle 64Abstracting Access to Services and Resources 67Reusing Bean Definitions 72Using Post-Processors to Handle Customized Beans and Containers 75

Summary 8 1

Chapter 3: Advanced Container Concepts 83.

Abstractions for Low-Level Resources 84The Application Context as a ResourceLoader 84The Application Context as a Message Source 87

Application Events 89Managing the Container 9 1

Resource Location Paths in ApplicationContext Constructors 92Declarative Usage of Application Contexts 93Splitting Up Container Definitions into Multiple Files 95Strategies for Handling Components 97Singletons for Accessing the Container 99

Some Convenience Factory Beans 99PropertyPathFactoryBean 99FieldRetrievingFactoryBean 101MethodlnvokingFactoryBean 101

Property Editors Provided by Spring 102Strategies for Testing 103

Unit Tests 103Tests That Use the Spring Container 106

Alternatives to XML 108Definitions from Properties Files 108Programmatic Bean Definitions 110Other Formats 110

References 110Summary 11,1

AOP

Goals 113Assumptions 114Example 114

XII

Contents

Spring's AOP Framework 118The Interceptor Chain 118Pros and Cons 118Advice 119Pointcuts 125Advisors 130Integration with the Spring loC Container 132Examining and Manipulating Proxy State at Runtime 145Programmatic Proxy Creation 146

Using Advanced Features of Spring's AOP Framework 147TargetSources 147Terminating the Interceptor Chain Early 153Using Introduction 153Exposing the Current Proxy 156Exposing the Current Methodlnvocation 157Understanding Proxy Types 158Debugging and Testing 159Miscellaneous 161

Integration with Other AOP Frameworks 163Goals 164Aspect! Integration 164AspectWerkz 169

References 169Summary 170

Chapter 5: DAO Support and JDBC Framework 1ZX

The Data Access Object Pattern 172Introducing Spring's JDBC Framework 173

Motivation: Issues with Direct Use of JDBC 173How Spring Can Help 175A Simple Example 176

Building the Data Access Layer for the Sample Application 177Data Model for the Sample Application 177DataSource f 178Exception Translation 180

Operations with JdbcTemplate 183Use of Callback Methods 183JdbcTemplate Convenience Methods 184Basic Queries Using the JdbcTemplate 185Basic Updating with JdbcTemplate , 186Advanced Use of JdbcTemplate 187Support for RowSet 188

viii

Contents

Using the RDBMS Operation Classes 189SqIQuery and MappingSqIQuery 190Inserts and Updates with SqlUpdate 192Updating a ResultSet Using UpdatableSqIQuery 193Generating Primary Keys 194Retrieving Database-Generated Keys 195Calling a Stored Procedure 196

Advanced Concepts 199Running Spring JDBC in an Application Server 199Using Custom Exception Translations 201Reading and Writing LOB Data 203Batch Updates 208Advanced Use of Stored Procedures 210

Additional Considerations 214Performance 214When to Use JDBC Versus O/R Mapping 215JDBC Versions and J2EE Versions 215

Summary 215

Chapter 6: Transaction and Resource Management 21Z

Background 217What Is a Transaction? 217The ACID Properties 218Concurrency Control 220

Transactions and J2EE 220Local Transactions 221Global/Distributed Transactions 221Transaction Propagation 221Transaction Demarcation 221

An Example of Spring's Transaction Support 222Introducing Spring's Transaction Abstraction 224

Overview of Choices for Transaction Control 225Transaction Definition 226Transaction Status 229Transaction Demarcation Strategies 229Transaction Management Strategies 242

DataSource Declarations 251Local Unpooled 251Local Pooled 252JNDI , 253Choosing Between Local and JNDI DataSource 253

Summary 254

Contents

Chapter 7: Object/Relational Mapping 255

Background 256Basic 0/R Mapping 256Object Query Languages 257Transparent Persistence 258When to Choose O/R Mapping 258

O/R Mapping Support in Spring 259Data Access Objects 259Transaction Management 260

iBATIS SQL Maps 261Mapping File 261DAO Implementation 263Setup in a Spring Context 265Transaction Management 266iBATIS Summary 267

Hibernate 268Mapping File 269DAO Implementation 270Setup in a Spring Context 273Transaction Management 276Open Session in View 282BLOB/CLOB Handling 285Hibernate: Summary 287

JDO 288Persistent Object Lifecycle 289DAO Implementation 289Setup in a Spring Context 291Transaction Management 293PersistenceManager Lifecycle 294Open PersistenceManager in View 295JDO Dialect 297JDO: Summary 298

Other O/R Mapping Tools 299Apache OJB * 299TopLink 300Cayenne 302JSR-220 Persistence 302

Summary 302

Chapter 8: Lightweight Remotlng 305

Concepts and Scope 306

YV

Contents

Common Configuration Style 307Hessian and Burlap 309

Accessing a Service 310Exporting a Service 312

HTTP Invoker 313Accessing a Service 314Exporting a Service 315Customization Options 316

RMI 317Accessing a Service 318Stub Lookup Strategies 320Exporting a Service 322Customization Options 323RMI-IIOP 323

Web Services via JAX-RPC 324Accessing a Service 326Exporting a Service 328Custom Type Mappings 330

Summary 332

Chapter 9: Supporting Services 335

JMS 335Introduction 336Motivation for Spring's JMS Support 337JMS Access via a Template 338Exception Handling 340ConnectionFactory Management 340Message Converters 340Destination Management 342Transaction Management 343JmsGatewaySupport 343The Future 345

Scheduling with Spring 345Timers Versus Quartz 346Timers 346Quartz 348

Sending Email with Spring 354Getting Started •• 354Reusing an Existing Mail Session 355Mail Sending Using COS „ 356Generic Mail Manager 356

v\/i

Contents

ScriptingConsistent ModelOther Scripting Languages

Summary

Chapter 10: Acegl Security System for Spring

361361365365

367

Enterprise Application Security ChoicesTypical RequirementsAcegi Security in a NutshellJava Authentication and Authorization ServiceServlet Specification

Acegi Security FundamentalsAuthenticationStoring the Authentication ObjectAuthorizationDomain Object Instance Security

Example CodeIntroducing the SampleSecurity Unaware ImplementationSecurity ApproachAuthenticationAuthorization

Summary

367367368372375377377381383386389389389391391392395

397

Deciding on the Need for EJBsAccessing EJBs

The Boilerplate ApproachThe Spring Approach

Implementing EJBs with SpringStateless Session BeansStateful Session BeansMessage Driven BeansA Digression into XDoclet

Singleton Container Access, Good or Evil?ContextSingletonBeanFactoryLocator and SingletonBeanFactoryLocatorA Shared Cpntext as the Parent ofa Web-App Application ContextUsing a Shared Context from EJBs

397399399400407407410411412413414

416419

vwii

IContents

Testing Concerns 420Implement Business Functionality in POJO Delegate 420Use a Mock EJB Container 420Integration Testing Inside the AppServer 421

Summary 422

Chapter 12: Web MVC Framework 423

A Simple Example 423General Architecture 425

Web MVC Concepts 426Generic Web MVC Using a Dispatcher and Controllers 427Requirements for a Good Web MVC Framework 428Spring's Web MVC Equivalents 429

Infrastructural Components 430The DispatcherServlet 431The WebApplicationContext 434

Workflow Involved with Handling Requests 436Common Layout of a Spring MVC Web Application 440HandlerMappings 4 4 1

BeanNameUrlHandlerMapping 442SimpleUrlHandlerMapping 443CommonsPathMapUrlHandlerMapping 444More Than One HandlerMapping 445

HandlerExecutionChain and Interceptors 446WebContentlnterceptor 447UserRoleAuthorizationlnterceptor 448Other Handler Interceptors Provided by Spring MVC 449

Handlers and Their Adapters 449ModelAndView and ViewResolvers 450

UrIBasedViewResolvers 450BeanNameViewResolver and XmlViewResolver 451ResourceBundleViewResolver 451Chaining View Resolvers 452

Locale Changing and Resolution 454HandlerExceptionResolvers 456Controllers 458

WebContentGenerator 458AbstractController 459UrIFilenameViewController 459ParameterizableViewController , 460MultiActionController 460

vv/iii

Contents

Data Binding 461Convenient Functionality When Working with Data Binding 463

Real-World Examples of Using Controllers 464Viewing a List of Performances Using the AbstractController 464Making a Reservation 466

Wizard Functionality 474Basic Configuration 474Template Methods 475Flow of a Wizard 476Page Changes, Numbering, and Other Actions 476

Extending Spring's Handler Infrastructure 478Uploading Files 478

Configuring the Multipart Resolver 479Creating a Form to Upload a File 479Handling Uploaded Data 479

Testing Your Controllers 4 8 1Testing Without the Application Context 481More Extensive Testing Using Mock Objects 483Testing Using the Complete Application Context 484Other Ways to Test a Web Application 485

Summary 485

Chapter 13: Web View Technologies 487

An Example 488General Configuration 488JavaServer Pages 489FreeMarker 489Generating PDFs Using iText 490

Considerations When Choosing a Technology 491View Objects and Models 491Features Offered by the AbstractVlew 493

Issuing a New Request Using the RedirectView 494Using View Prefixes to Issue Forwards or Redirects 495

JavaServer Pages 496Configuring Your Application to Use JSP 497Creating Forms Using Custom Tags 497Using Tag Files to Create Reusable Elements 504

Velocity and .FreeMarker 505Configuring the View Resolver 505Using the Form Simplification Macros „ 507

Y I Y

Contents

TilesViews Based on XML and XSLTExcel and Other Document-Based Views

Generating an Excel File from Our List of ShowsUsing a Template as a Basis for Your Excel FileOther Document-Based ViewsUsing a Handlerlnterceptor to Distinguish Between HTML and Excel

Implementing Custom ViewsView and AbstractViewImplementing a View Generating XML from a Data ObjectConsiderations When Implementing Custom Views

Summary

Chapter 14: Integrating with Other Web Frameworks

511514515516517517517519520520522522

523

Considerations When Choosing an MVC FrameworkComparing the Traditional Web MVC Frameworks

Integrating with Spring: Core ConceptsWebWork Integration

Setting Up the ObjectFactoryStruts Integration

Using ActionSupportUsing DelegationRequestProcessor and DelegationActionProxyUsing an Auto Wiring Base Action

Tapestry IntegrationGetting Beans for TapestryThe Page ClassThe Page DefinitionThe Page TemplateTapestry Integration Final Thoughts

JavaServer Faces IntegrationSummary

Chapter 15: The Sample Application

523524534536536537538539542543543544544545547547549

551

Choice of Server TechnologiesApplication LayersPersistence Layer

Data ModelDomain Object ModelObject/Relational MappingDAO Implementation

552552554554556558561

Data Access ContextBusiness Service Layer

ServicesApplication Context

Web LayerFlow Through the ApplicationConfiguring the Application via web.xmlWeb ControllersView Technology

Comparison with the J2EE Design and Development ImplementationSimpler TechnologyDatabase Changes

Server ConfigurationMySQLTomcat

Build and DeploymentCreating and Loading the Database TablesBuilding the Application and Deploying It to the Tomcat Server

Summary

Chapter 16: Conclusion

Problems Solved by SpringThe Spring SolutionGuidelines for Spring Development

Technology ChoicesLayer by LayerStructuring ApplicationsTesting Your Applications

Related ProjectsAcegi Security for SpringOther Projects

Spring in Non-J2EE EnvironmentsTo Find Out More

Books and ArticlesOnline ResourcesSample Applications

The Future

Appendix A: Requirements for the Sample Application

Contents

563563564565566566568569571572572573573573574574574575575

577

577578581581583589592594594595596596597597597598

601

Overview 601

vvi

Contents

User PopulationsPublic Internet UsersBox Office UsersAdministrators

AssumptionsScope LimitationsDelivery ScheduleInternet User Interface

Basic WorkflowError HandlingApplication Screens

Non-Functional RequirementsHardware and Software Environment

602602602603603604604605605606606618619

Index 621