fast track to spring 3.x and spring mvc/rest · fast track to spring 3.x and spring mvc/rest on...

153
Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Upload: duongdat

Post on 11-Nov-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Fast Track

to Spring 3.x

and Spring MVC/REST

on Eclipse/Tomcat

Student Guide

LearningPatterns, Inc. Courseware

Evaluation Copy

Page 2: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright © 2004-13 LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. [email protected] | www.learningpatterns.com Global Courseware Services 262 Main St. #12 | Beacon NY, 12508 USA 212.487.9064 voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns Inc. All other products referenced herein are trademarks of their respective holders.

Evaluation Copy

Page 3: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved i

Table of Contents – Fast Track to Spring 3.x and Spring MVC/REST

Fast Track to Spring 3.x and Spring MVC/REST ____________________________ 1 Workshop Overview _______________________________________________________________ 2 Workshop Objectives ______________________________________________________________ 3 Workshop Agenda_________________________________________________________________ 4 Typographic Conventions ___________________________________________________________ 5 Labs ____________________________________________________________________________ 6 Release Level_____________________________________________________________________ 7

Session 1: Introduction to Spring __________________________________________ 8 Lesson Objectives _________________________________________________________________ 9 Overview _______________________________________________________________________ 10 The Challenge of Enterprise Applications______________________________________________ 11 Shortcomings of Java/Java EE ______________________________________________________ 12 What is Spring? __________________________________________________________________ 13 The Spring Modules ______________________________________________________________ 14 The Spring Distribution____________________________________________________________ 15 The Spring Distribution____________________________________________________________ 16

Lab 1.1 – Setting Up the Environment ____________________________________________ 17 Spring Introduction ________________________________________________________ 33

Managing Beans _________________________________________________________________ 34 A Basic Spring Application_________________________________________________________ 35 Some Bean Classes _______________________________________________________________ 36 Configuration Metadata____________________________________________________________ 37 Declaring Beans__________________________________________________________________ 38 The Spring Container _____________________________________________________________ 39 Working With Spring _____________________________________________________________ 40 A Simple Spring Example __________________________________________________________ 41 Why Bother? ____________________________________________________________________ 42 Some BeanFactory/ApplicationContext API____________________________________________ 43

Lab 1.2 – Hello Spring World____________________________________________________ 44 Dependencies and Dependency Injection _______________________________________ 49

Dependencies Between Objects______________________________________________________ 50 Example of a Direct Dependency ____________________________________________________ 51 Dependency Inversion Principal _____________________________________________________ 52 Example of Dependency Inversion ___________________________________________________ 53 Example of Dependency Inversion ___________________________________________________ 54 Dependency Injection (DI) in Spring _________________________________________________ 55 Dependency Injection Configuration__________________________________________________ 56 Dependency Injection Example______________________________________________________ 57 Advantages of Dependency Injection _________________________________________________ 58 Dependency Injection Reduces Coupling ______________________________________________ 59

Lab 1.3 – Dependency Injection __________________________________________________ 60 Review Questions ________________________________________________________________ 65 Lesson Summary _________________________________________________________________ 66 Lesson Summary _________________________________________________________________ 67

Session 2: More About Bean Properties ____________________________________ 68 Lesson Objectives ________________________________________________________________ 69

Evaluation Copy

Page 4: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved ii

Working with Properties ____________________________________________________ 70 Configuring Value Based Properties __________________________________________________ 71 Using Value Based Properties _______________________________________________________ 72 Property Conversions _____________________________________________________________ 73 Constructor Injection ______________________________________________________________ 74 Constructor Argument Resolution____________________________________________________ 75 Constructor Argument Resolution____________________________________________________ 76 Constructor Argument Resolution____________________________________________________ 77 XML Shortcuts - p: and c: Namespaces _______________________________________________ 78 Setter Injection vs. Constructor Injection ______________________________________________ 79 Setter Injection vs. Constructor Injection ______________________________________________ 80

Lab 2.1 – Spring Configuration __________________________________________________ 81 Collection Valued Properties _________________________________________________ 91

Working with Collections __________________________________________________________ 92 Collection Property Example________________________________________________________ 93 Configuring <list> and <set> Properties _______________________________________________ 94 Configuring Collection of Bean References ____________________________________________ 95 Map Valued Properties ____________________________________________________________ 96 java.util.Properties Valued Properties _________________________________________________ 97

Lab 2.2 – Collection Valued Properties ____________________________________________ 98 Additional Capabilities_____________________________________________________ 103

- Factory Methods - ______________________________________________________________ 104 Instance Factory Methods _________________________________________________________ 105 - Bean Aliases - _________________________________________________________________ 106 - Bean Definition Inheritance - _____________________________________________________ 107 Inheritance Example _____________________________________________________________ 108 - SpEL: Spring Expression Language - _______________________________________________ 109 Other SpEL Capabilities __________________________________________________________ 110 - Autowiring - __________________________________________________________________ 111 Autowiring byName Example ______________________________________________________ 112 Autowiring byType ______________________________________________________________ 113 Pros and Cons of Autowiring ______________________________________________________ 114 To Autowire or Not to Autowire ____________________________________________________ 115 Review Questions _______________________________________________________________ 116 Lesson Summary ________________________________________________________________ 117 Lesson Summary ________________________________________________________________ 118

Session 3: The Spring Container and API _________________________________ 119 Lesson Objectives _______________________________________________________________ 120

ApplicationContext________________________________________________________ 121 ApplicationContext Interface ______________________________________________________ 122 ApplicationContext Implementations ________________________________________________ 123 Constructors____________________________________________________________________ 124 Using an ApplicationContext ______________________________________________________ 125 Spring Resource Access __________________________________________________________ 126 Built-in Resource Implementations __________________________________________________ 127

Lab 3.1 – More about ApplicationContexts _______________________________________ 128 Bean Scope and Lifecycle _________________________________________________________ 132 Bean Scope ____________________________________________________________________ 133 Specifying Bean Scope ___________________________________________________________ 134 Inner Beans ____________________________________________________________________ 135 Compound Names _______________________________________________________________ 136 Depends On ____________________________________________________________________ 137 Bean Creation Lifecycle __________________________________________________________ 138

Evaluation Copy

Page 5: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved iii

Bean Creation Lifecycle Details ____________________________________________________ 139 Using the Lifecycle Interfaces for Beans______________________________________________ 140 Bean Destruction Lifecycle ________________________________________________________ 141 BeanPostProcessor ______________________________________________________________ 142 @PostConstruct and @PreDestroy __________________________________________________ 143 Event Handling _________________________________________________________________ 144

Lab 3.2 – Bean Lifecycle _______________________________________________________ 145 Annotation Driven Configuration ____________________________________________ 151

Annotations in Spring ____________________________________________________________ 152 Enabling Spring Annotations_______________________________________________________ 153 @Component and Auto-Detecting Beans _____________________________________________ 154 Annotation-based Bean Definition and DI ____________________________________________ 155 Complete Declarations Using Annotations ____________________________________________ 156 XML Config for Annotations and Scanning ___________________________________________ 157 Other Stereotype Annotations ______________________________________________________ 158 @Resource - Additional Uses ______________________________________________________ 159 @Autowired ___________________________________________________________________ 160 @Autowired Examples ___________________________________________________________ 161 Qualifiers______________________________________________________________________ 162 Lifecycle Annotations ____________________________________________________________ 163 Annotation Configuration - Pro / Con ________________________________________________ 164 A Note on the XML Configuration __________________________________________________ 165 A Brief Note on Annotations_______________________________________________________ 166 Annotation Definition Example_____________________________________________________ 167

Lab 3.3 – Spring Annotations___________________________________________________ 168 Java-based Configuration __________________________________________________ 173

Java Configuration Overview ______________________________________________________ 174 Using Java-based Configuration ____________________________________________________ 175 Dependency Injection ____________________________________________________________ 176 More on How it Works ___________________________________________________________ 177 Dependencies Between Configuration Classes _________________________________________ 178 Other Usage Scenarios____________________________________________________________ 179 Classpath Scanning ______________________________________________________________ 180 Other @Bean Capabiliites _________________________________________________________ 181 Java-based Configuration - Pro / Con ________________________________________________ 182

[Optional] Lab 3.4 – Java-based Config __________________________________________ 183 Maven and Spring_________________________________________________________ 188

About Maven___________________________________________________________________ 189 How We'll Work With Maven______________________________________________________ 190 The POM (Project Object Model) ___________________________________________________ 191 POM - Required Elements_________________________________________________________ 192 POM - External Dependencies _____________________________________________________ 193 Maven Artifacts for Spring ________________________________________________________ 194 Repositories ____________________________________________________________________ 195 Maven Project Structure __________________________________________________________ 196 Eclipse / Maven Integration________________________________________________________ 197 The Lab _______________________________________________________________________ 198 [Optional] Lab 3.5 – Using Maven __________________________________________________ 199

Lab 3.5 – Using Maven ________________________________________________________ 200 Review Questions _______________________________________________________________ 210 Lesson Summary ________________________________________________________________ 211 Lesson Summary ________________________________________________________________ 212 Lesson Summary ________________________________________________________________ 213

Evaluation Copy

Page 6: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved iv

Session 4: Database Access With Spring __________________________________ 214 Lesson Objectives _______________________________________________________________ 215

Overview ________________________________________________________________ 216 DAO Support___________________________________________________________________ 217 Datasources ____________________________________________________________________ 218 Configuring the DataSource _______________________________________________________ 219 Looking up a DataSource in JNDI___________________________________________________ 220

[Optional] Using Spring with Hibernate_______________________________________ 221 Hibernate Overview______________________________________________________________ 222 Typical Hibernate Configuration File ________________________________________________ 223 Using Hibernate Directly__________________________________________________________ 224 Spring Support for Hibernate ______________________________________________________ 225 LocalSessionFactoryBean _________________________________________________________ 226 Configuring a Hibernate Session Factory _____________________________________________ 227 Contextual Sessions______________________________________________________________ 228 Spring Free DAO________________________________________________________________ 229 What Approach to Use ___________________________________________________________ 230

[Optional] Using Spring with JPA ___________________________________________ 231 Template Support for JPA _________________________________________________________ 232 Managing the EntityManager ______________________________________________________ 233 LocalContainerEntityManagerFactoryBean ___________________________________________ 234 Container-Managed EntityManager _________________________________________________ 235 JEE: Obtaining an EntityManager From JNDI _________________________________________ 236 LocalEntityManagerFactoryBean ___________________________________________________ 237 Additional Spring Configuration ____________________________________________________ 238 Spring Configuration Example _____________________________________________________ 239 JPA Data Access Object __________________________________________________________ 240 Extended Persistence Context ______________________________________________________ 241

[Optional] Lab 4.1 – Integrating Spring and JPA __________________________________ 242 Review Questions _______________________________________________________________ 253 Lesson Summary ________________________________________________________________ 254 Lesson Summary ________________________________________________________________ 255

Session 5: Transactions ________________________________________________ 256 Lesson Objectives _______________________________________________________________ 257

Spring Transaction Management ____________________________________________ 258 Transaction (Tx) Overview ________________________________________________________ 259 Transaction Lifecycle ____________________________________________________________ 260 Transaction Managers ____________________________________________________________ 261 Configuring Transaction Managers __________________________________________________ 262 JTA Transaction Manager _________________________________________________________ 263 Spring Declarative Transaction Management __________________________________________ 264 Spring Transactional Scope________________________________________________________ 265 Transaction Propagation __________________________________________________________ 266 Transaction Attributes for Propagation _______________________________________________ 267 MANDATORY _________________________________________________________________ 268 NESTED ______________________________________________________________________ 269 NEVER _______________________________________________________________________ 270 NOT_SUPPORTED _____________________________________________________________ 271 REQUIRED____________________________________________________________________ 272 REQUIRES_NEW ______________________________________________________________ 273 SUPPORTS ____________________________________________________________________ 274 Transaction Example _____________________________________________________________ 275

Evaluation Copy

Page 7: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved v

Transaction Attributes – Some Choices ______________________________________________ 276 Transaction Attributes - Some Choices _______________________________________________ 277 Specifying Transaction Attributes ___________________________________________________ 278 Specifying Transaction Attributes ___________________________________________________ 279 Additional Transactional Attributes _________________________________________________ 280 Transactional Attributes Guidelines _________________________________________________ 281 Rolling Back and Exceptions ______________________________________________________ 282

Lab 5.1 – Spring Transactions __________________________________________________ 283 Spring Proxies and Direct Invocation ________________________________________________ 292 Example – Invoking Directly ______________________________________________________ 293 Example – Invoking Directly ______________________________________________________ 294 Load-Time Weaving _____________________________________________________________ 295 Spring's Load-Time Weaving ______________________________________________________ 296

[Optional] Lab 5.2: Load-Time Weaving _________________________________________ 297 [Optional] XML Configuration ______________________________________________ 302

Specifying Transactions Using XML ________________________________________________ 303 Spring Transactions and AOP ______________________________________________________ 304 Defining a Pointcut ______________________________________________________________ 305 Linking Advice With Pointcuts _____________________________________________________ 306 <tx:method> Attributes ___________________________________________________________ 307 Why Use XML Configuration______________________________________________________ 308 Review Questions _______________________________________________________________ 309 Lesson Summary ________________________________________________________________ 310

Session 6: Web Applications with Spring MVC ____________________________ 311 Lesson Objectives _______________________________________________________________ 312

Integration with Java EE ___________________________________________________ 313 Spring and Java EE ______________________________________________________________ 314 Overview of Java EE Web Applications ______________________________________________ 315 Web Application Structure ________________________________________________________ 316 Web Application Components______________________________________________________ 317 ApplicationContext and Web Apps__________________________________________________ 318 Configuring ContextLoaderListener _________________________________________________ 319 Using the Application Context _____________________________________________________ 320

Lab 6.1 – Spring and the Web __________________________________________________ 321 Spring MVC Basics________________________________________________________ 337

What is Spring MVC? ____________________________________________________________ 338 General MVC Architecture ________________________________________________________ 339 MVC Pattern flow _______________________________________________________________ 340 Spring MVC Architecture _________________________________________________________ 341 Simple Search App Model - Servlets/JSP _____________________________________________ 342 Simple Search App Model - Spring MVC_____________________________________________ 343 DispatcherServlet _______________________________________________________________ 344 DispatcherServlet Initialization _____________________________________________________ 345 Controllers_____________________________________________________________________ 346 A Very Simple Controller _________________________________________________________ 347 Control Flow ___________________________________________________________________ 348

Lab 6.2 – Spring MVC Basics___________________________________________________ 349 @RequestParam – Parameter Binding _______________________________________________ 355 Returning Model Data ____________________________________________________________ 356 Returning Model Data ____________________________________________________________ 357 The JSP Pages __________________________________________________________________ 358 Other Handler Method Capabilities__________________________________________________ 359 Example – Other Handler Capabilities _______________________________________________ 360

Evaluation Copy

Page 8: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved vi

Lab 6.3 – Parameters and Models _______________________________________________ 361 View Resolvers _________________________________________________________________ 365 Controller Using Logical Names____________________________________________________ 366 Other View Resolvers ____________________________________________________________ 367

Lab 6.4 – View Resolvers ______________________________________________________ 368 Forms and Command Objects_______________________________________________ 371

Spring MVC Form Tags __________________________________________________________ 372 A JavaBean Command Class_______________________________________________________ 373 Working with Model Classes ______________________________________________________ 374 Request Handling Flow ___________________________________________________________ 375 Exposing Reference Data in the Model _______________________________________________ 376

Lab 6.5 – Forms and Command Objects__________________________________________ 377 Review Questions _______________________________________________________________ 384 Lesson Summary ________________________________________________________________ 385 Lesson Summary ________________________________________________________________ 386

Session 7: Spring Security Overview______________________________________ 387 Spring Security _________________________________________________________________ 388 Spring Web Security - web.xml_____________________________________________________ 389 Spring Web Security - Spring Configuration __________________________________________ 390 Spring Web Security - Spring Configuration __________________________________________ 391 More <security:http> Capabilities ___________________________________________________ 392 Other User Details Services________________________________________________________ 393

Lab 7.1 – Spring Web Security__________________________________________________ 394 Method Security ________________________________________________________________ 399 Method Security - Annotations _____________________________________________________ 400 Method Security - Pointcut Expressions ______________________________________________ 401 Method Security - XML Configuration_______________________________________________ 402

Lab 7.2 – Method Security _____________________________________________________ 403 Session 8: RESTful Services with Spring __________________________________ 407

Session Objectives_______________________________________________________________ 408 REST Overview __________________________________________________________ 409

Overview of REST ______________________________________________________________ 410 REST Details___________________________________________________________________ 411 Example: Accessing REST Resources _______________________________________________ 412 What is a REST Service Interface? __________________________________________________ 413 URI Templates for Client Data _____________________________________________________ 414 REST URI with a URI Template____________________________________________________ 415 Summary of REST Characteristics __________________________________________________ 416 Comparison of REST and SOAP____________________________________________________ 417

REST and Spring MVC ____________________________________________________ 418 Spring Support for REST _________________________________________________________ 419 A Simple RESTful Controller Example ______________________________________________ 420 Using @RequestMapping and @PathVariable _________________________________________ 421 @ResponseBody for Generating a Response __________________________________________ 422 @ResponseBody Example ________________________________________________________ 423 Additional URI Mapping Capabiliites________________________________________________ 424

Lab 8.1 – A Simple REST Service _______________________________________________ 425 More Complex Response Objects ___________________________________________________ 430 HTTP Message Converters ________________________________________________________ 431 Returning an XML Representation __________________________________________________ 432 Returning a JSON Representation___________________________________________________ 433 Narrowing Controller Mappings ____________________________________________________ 434

Lab 8.2 – Returning XML and JSON ____________________________________________ 435

Evaluation Copy

Page 9: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved vii

Client-Side Access to RESTful Service ________________________________________ 443 REST Client Requirements ________________________________________________________ 444 RestTemplate Overview __________________________________________________________ 445 getForObject() Details ____________________________________________________________ 446 Conventions for RestTemplate Methods ______________________________________________ 447 RestTemplate Method Variations ___________________________________________________ 448 getForObject() Using Map_________________________________________________________ 449 Other RestTemplate Methods ______________________________________________________ 450

Lab 8.3 – A Client with RestTemplate____________________________________________ 451 RestTemplate.getForEntity() _______________________________________________________ 461 HttpEntity and HttpHeaders _______________________________________________________ 462 Accessing Headers_______________________________________________________________ 463 RestTemplate.exchange() _________________________________________________________ 464 Setting Headers on a Request ______________________________________________________ 465 Error Handling__________________________________________________________________ 466 Summary of RestTemplate Usage ___________________________________________________ 467

Lab 8.4 – [Optional] Accessing Headers __________________________________________ 468 Common REST Patterns ___________________________________________________ 473

The REST Methods ______________________________________________________________ 474 GET: Retrieve Information ________________________________________________________ 475 POST: Add New Information ______________________________________________________ 476 Server: POST Controller - Details___________________________________________________ 477 Server: Setting Location Header for POST ____________________________________________ 478 Client: RestTemplate for POST_____________________________________________________ 479 PUT: Update Information _________________________________________________________ 480 Client: RestTemplate for PUT______________________________________________________ 481 DELETE: Remove an Entity _______________________________________________________ 482 Client: RestTemplate for DELETE __________________________________________________ 483

[Optional] Lab 8.5: More REST Operations _____________________________________ 484 Review Questions _______________________________________________________________ 492 Lesson Summary ________________________________________________________________ 493 Lesson Summary ________________________________________________________________ 494

[Optional] Session 9: Aspect Oriented Programming ____________________________ 495 Lesson Objectives _______________________________________________________________ 496 Overview ______________________________________________________________________ 497 The Issue with Crosscutting Concerns _______________________________________________ 498 Crosscutting Illustrated ___________________________________________________________ 499 Aspect Oriented Programming (AOP) Defined_________________________________________ 500

Spring AOP Introduction___________________________________________________ 501 Spring AOP With AspectJ Annotations ______________________________________________ 502 Defining an Aspect with @AspectJ__________________________________________________ 503 Defining a Pointcut ______________________________________________________________ 504 Defining a Pointcut ______________________________________________________________ 505 Defining Advice ________________________________________________________________ 506 Configuring Spring ______________________________________________________________ 507 Triggering Advice _______________________________________________________________ 508 More on How Spring AOP Works___________________________________________________ 509

Lab 9.1 – Hello AOP World ____________________________________________________ 510 Pointcut Expressions and Advice ____________________________________________ 517

Pointcut Expressions _____________________________________________________________ 518 Sample execution Designator Patterns _______________________________________________ 519 Sample execution Designator Patterns _______________________________________________ 520 Other Designators Available in Spring AOP___________________________________________ 521

Evaluation Copy

Page 10: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

20130401 Copyright © 2004-13, LearningPatterns Inc. All rights reserved viii

Sample Designator Patterns________________________________________________________ 522 Combining Pointcut Expressions____________________________________________________ 523 Kinds of Advice_________________________________________________________________ 524 Advice Examples________________________________________________________________ 525 Around Example ________________________________________________________________ 526 Around Example ________________________________________________________________ 527

Lab 9.2 – More Spring AOP ____________________________________________________ 528 XML Based AOP Support __________________________________________________ 533

Defining Aspects Using XML______________________________________________________ 534 AOP XML Configuration Example__________________________________________________ 535 Specifying Advice With XML _____________________________________________________ 536

Lab 9.3 – Using AOP XML Configuration [Optional] _______________________________ 537 Other Considerations ______________________________________________________ 541

Spring Proxies and Direct Invocation ________________________________________________ 542 More on Spring Proxies___________________________________________________________ 543 Issues with AOP ________________________________________________________________ 544 Issues with AOP ________________________________________________________________ 545 Is AOP Worth It ? _______________________________________________________________ 546 Other AOP Capabilities and Functionality ____________________________________________ 547 Review Questions _______________________________________________________________ 548 Lesson Summary ________________________________________________________________ 549 Lesson Summary ________________________________________________________________ 550

Recap ______________________________________________________________ 551 Recap of what we've done _________________________________________________________ 552 What Else is There_______________________________________________________________ 553 Resources______________________________________________________________________ 554

Evaluation Copy

Page 11: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 120130401

Fast Track to Spring 3.x and Spring MVC/REST

Fast Track to Spring 3.x and Spring MVC/REST

The Java Developer Education Series

Introduction

Evaluation Copy

Page 12: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 220130401

Fast Track to Spring 3.x and Spring MVC/REST

Workshop Overview

This is an in-depth course covering the use of the Spring 3 framework to build enterprise applications using Java

The course, at a high level, covers the following areas of Spring technology

– Core features of Spring– Data Access Features– Transaction Support– Web Application Support including Spring MVC– Spring Security Overview– Building RESTful Services with Spring– Aspect Oriented Programming (AOP)

Introduction

Evaluation Copy

Page 13: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 320130401

Fast Track to Spring 3.x and Spring MVC/REST

Workshop Objectives

To understand the Spring framework and use its capabilities, including:Spring Core: Dependency Injection (DI) and lifecycle management of application objects– Using the Spring API and Spring configuration to write Spring programs– Configuration covers both XML and annotations

Data Access: Data access via Spring's data support– DataSource support– Hibernate and JPA-based DAOs

Transactions: Control transactions declaratively with Spring– Use the Spring annotations and XML configuration elements

Web: Integrate Spring with Web applications and understand the basic structure and use of Spring MVCSecurity: Understand the architecture and basic use of Spring SecurityREST: Understand REST principals, and build REST services with SpringAOP: Use Spring's AOP (Aspect Oriented Programming) capabilities toinject crosscutting concerns

Introduction

Evaluation Copy

Page 14: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 420130401

Fast Track to Spring 3.x and Spring MVC/REST

Workshop Agenda

Session 1: Introduction to Spring

Session 2: More About Bean Properties

Session 3: The Spring Container and API

Session 4: Database Access With Spring

Session 5: Transactions

Session 6: Web Applications with Spring MVC

Session 7: Spring Security Overview

Session 8: RESTful Services with Spring

Session 9: [Optional] Aspect Oriented Programming (AOP)

Introduction

Evaluation Copy

Page 15: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 520130401

Fast Track to Spring 3.x and Spring MVC/REST

Typographic Conventions

Code in the text uses a fixed-width code font, e.g.:

JavaTeacher teacher = new JavaTeacher()

–Code fragments use the same font, e.g. teacher.teach()

–We bold/color text for emphasis

–Filenames are in italics, e.g. JavaInstructor.java

–We sometimes denote more info in the notes with a star *

–Longer code examples appear in a separate code box - e.g.

package com.javatunes.teach;public class JavaInstructor implements Teacher {

public void teach() {System.out.println("BeanFactories are way cool");

}}

* If we had additional information about a starred item in the slide, it would appear here in the notes

We might also put other related information that generally pertains to the material in the slide

Introduction

Evaluation Copy

Page 16: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 620130401

Fast Track to Spring 3.x and Spring MVC/REST

Labs

The workshop has numerous hands-on lab exercises, structured as a series of brief labs – Many follow a common fictional case study called JavaTunes

• An online music store– The labs are in the course book, and include detailed instructions

Setup zip files are provided with skeleton code for the labs– Students add code focused on the topic they're working with– There is a solution zip with completed lab code

Lab slides have an icon like in the upper right corner of this slide– The end of a lab is marked with a stop like this one:

Lab

STOP

Introduction

Evaluation Copy

Page 17: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 720130401

Fast Track to Spring 3.x and Spring MVC/REST

Release Level

This manual has been tested with, and contains instructions for, running the labs using the following platforms:

– Spring 3.2 (tested with 3.2.2)• The material is compatible with Spring 3.1 (see notes)

– Spring Security 3.1 (tested with 3.1.3)– Java 6 or 7– Eclipse Java EE Edition (any fairly recent edition - tested with

4.2/Juno)– Tomcat 7.0.x for the Spring/Web material

Recent similar versions of the software will likely work except for potentially small configuration changes

Lab

Any 3.2 version of Spring should work– The APIs have not changed between 3.2 versions

The course material is compatible with Spring 3.1– However, in order to make the labs easy to run in a lab environment, we supply all the external

dependency jars required for the labs– We supply the dependency jars for 3.2, and some of these may be different than the ones needed

for 3.1– This is the main reason that you should stick with the versions we have tested with

All labs have been tested on Microsoft Windows using the software listed above– The labs should work on Unix with little modification, except for the database setup scripts,

which need to be use Unix shell scripts

Introduction

Evaluation Copy

Page 18: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 820130401

Fast Track to Spring 3.x

Session 1: Introduction to Spring

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 19: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 920130401

Fast Track to Spring 3.x

Lesson Objectives

Understand why we need the Spring Framework

Understand what Spring is, and how it simplifies enterprise application development with Java

Learn how Spring uses configuration information and Dependency Injection (DI)– To manage the beans (objects) in an application– To manage bean dependencies

Session 1: Introduction to Spring

Evaluation Copy

Page 20: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1020130401

Fast Track to Spring 3.x

Overview

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 21: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1120130401

Fast Track to Spring 3.x

The Challenge of Enterprise Applications

Enterprise applications have many complex requirements– Many types, with complex dependencies– Persistent data retrieved from / stored to a data store– Transactional requirements– Remote (distributed) access requirements– Web access requirements

Java / Java EE (Enterprise Edition) provides many capabilities to build enterprise applications– Java SE: Basic building blocks like Java primitives and core

libraries like Collections– Java EE: Enterprise technologies like EJB, Servlets/JSP, JDBC– However, there are shortcomings to the standard Java solution

There really is no formal definition of an enterprise applicationTypically though, some of the characteristics they have are:

– Used in a business environment, often in business-critical domains– Have some form of persistent storage– Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc)– Require some measure of scalability and fault tolerance

The definition of enterprise application is not important– Many Java applications share some of the requirements that we are outlining here

Session 1: Introduction to Spring

Evaluation Copy

Page 22: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1220130401

Fast Track to Spring 3.x

Shortcomings of Java/Java EE

Java/Java EE can have significant shortcomings, including:

Little support for managing the lifecycle of your objects and the dependencies between them– Managing large numbers of objects requires significant effort

Java EE is large and requires a fairly heavyweight app server– Even if using only a subset of capabilities (e.g. Web apps and

transactions), the application server generally supports all of them

Java EE has been difficult to use, and intrusive in its design– Not as big an issue now– Newer releases, such as EJB 3, are less intrusive

Though rich in functionality, due to its complexity, and the complexity of the systems being written, Java / Java EE can have a number of shortcomings for writing these systems

– These programs are composed of many collaborating objects and technologies, which require significant effort to manage

There are many design guidelines to help you with managing the collaboration of objects– Best practices, design patterns, etc.– These help you create a good design to make it easier to write and maintain your program– However, these still require that you write the code that manages the collaboration of objects

The newer Java and Java EE technologies have started to address the ease of use issue– The use of Java annotations (introduced in Java 5), new versions of existing technologies (such

as EJB 3), and completely new technologies such as JavaServer Faces (JSF) have made it significantly easier to use Java

Session 1: Introduction to Spring

Evaluation Copy

Page 23: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1320130401

Fast Track to Spring 3.x

What is Spring?

Lightweight framework to build enterprise applications– "Lightweight" meaning non-intrusive in your programming, and

allowing you to use only what you need

It includes the following capabilities– A Dependency Injection (Inversion of Control) container to

manage objects and their dependencies– A DAO package that abstracts JDBC and simplifies its use– An ORM package providing integration with technologies such as

Hibernate and JPA (Java Persistence API)– An AOP package for doing aspect-oriented programming– A Web package to integrate with Web technologies– An MVC package that provides a full Model-View-Controller

based Web framework for Web applications– A security framework for authentication and authorization

DAO stands for Data Access ObjectORM stands for Object-Relational Mapping

Session 1: Introduction to Spring

Evaluation Copy

Page 24: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1420130401

Fast Track to Spring 3.x

The Spring Modules

Module diagram from the Spring Reference Documentation

Session 1: Introduction to Spring

Evaluation Copy

Page 25: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1520130401

Fast Track to Spring 3.x

The Spring Distribution

Spring home page: http://www.springsource.org/– Can download Spring from this site

Framework distributed as a set of jar files– Each module packaged in its own archive

• e.g. spring-beans-3.2.2.RELEASE.jar– The core Spring download has the all the spring module jars, a

reference manual, and API docsSpring has many dependencies on external technologies– e.g. - Apache commons logging, jars for AOP, and more– Not included in the core Spring download

Maven is commonly used to manage Spring's dependencies– Project management tool - can automatically download needed

dependencies– Maven covered more later

You can download the distribution from http://www.springsource.org/download/community

In the past, the dependencies were available as a separate download from the Spring download pages– These are no longer provided

Session 1: Introduction to Spring

Evaluation Copy

Page 26: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1620130401

Fast Track to Spring 3.x

The Spring Distribution

Below left, is the folder structure of the core distribution– Below right, are some of the jars in the libs folder

• Note that there are source and javadoc jars also– At bottom is the docs folder

Session 1: Introduction to Spring

Evaluation Copy

Page 27: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1720130401

Fast Track to Spring 3.x

Lab 1.1 – Setting Up the Environment

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 28: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1820130401

Fast Track to Spring 3.x

Lab 1.1 – Set up the Environment

Overview: In this lab, we will become familiar with the lab structure, set up our working environment, and test it to make sure it is running well– The end goal is to compile and run an application that requires

the Spring libraries

Objectives: – Become familiar with the lab structure– Set up our environment– Write and run a simple application that requires Spring

Builds on previous labs: None

Approximate Time: 45-60 minutes

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 29: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 1920130401

Fast Track to Spring 3.x

Information Content and Task Content

Within a lab, information only content is presented in the normal way – the same as in the student manual pages– Like these bullets at the top of the page

Tasks that the student needs to perform are in a box with a slightly different look – to help you identify themAn example appears below

Tasks to PerformLook at these instructions, and notice the different look of thebox as compared to that above– Make a note of how it looks, as future labs will use this format

OK – Now get out your setup files; we're ready to start working

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 30: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2020130401

Fast Track to Spring 3.x

Setup Environment

Tasks to PerformMake sure Java is installed– Usually in a folder (for Java 7) like

C:\Program Files\Java\jdk1.7.0_nn– If not, then install it - it can be downloaded from:http://www.oracle.com/technetwork/java/javase/downloads/index.html

Check that Spring 3.2 is installed – likely in a folder like:C:\spring-framework-3.2.2.RELEASE– It is not required - you can use it for reviewing the documentation– We supply the needed jars in the setup– It can be downloaded from

http://www.springframework.org/download

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 31: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2120130401

Fast Track to Spring 3.x

Extract the Lab Setup Zip File

To set up the labs, you'll need the course setup zip file *– e.g.: LabSetup_Spring3x_Tomcat-Eclipse_20130401.zip

Our base working directory for this course will be C:\StudentWork\Spring

– This directory will be created when we extract the Setup zip– It includes a directory structure and files (e.g., Java files, XML

files, other files) that will be needed in the labs– All instructions assume that this zip file is extracted to C:\. If

you choose a different directory, please adjust accordingly

Lab

Tasks to PerformUnzip the lab setup file to C:\– This will create the directory structure, described in the next slide,

containing files that you will need for doing the labs

Depending on how your training environment, the setup files may be given to you in different ways, including:

– Present on the training machines as a zip file– Already unzipped on the training machine– Given to you by the instructor– Available as a network share or web download

Your instructor will let you know how to access them

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 32: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2220130401

Fast Track to Spring 3.x

Lab Directory Structure

StudentWork\Spring contains– Derby: Database files– SpringDependencies: jars for

Spring dependencies– SpringLibraries: Spring jars– workspace: Eclipse workspace

StudentWork\Spring\workspacewill contain the following folders:– common: shared files (if any)– LabNN : Folder for Lab NN– LabNN/src : Java source– LabNN/bin/ : compiled code

(Eclipse's standard location)

Lab

To make it easier to open command windows in the lab dirs, we've included a utility in the setup that allows you to right click on a folder to open a command prompt

– Not needed for Windows 7, where you can press and hold the shift key, then right click on a folder and select "Open Command Window Here"

– For earlier Windows versions, install this as follows: • Go to the Resources/CommandPromptHere folder• Right click on the .reg file there, and select Merge• Once you've done that, right clicking on a folder will show a Command Prompt Here

selection in the context menu - Select that to open a command prompt in the directory

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 33: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2320130401

Fast Track to Spring 3.x

General Instructions

Root lab folder for this lab is: C:\StudentWork\Spring\workspace\Lab01.1–Already exists in your workspace–You'll create a new Eclipse project in this folder, which contains starter files that we provide–In general, all the lab files are under this project/folder and instructions are given relative to this project/folder

Detailed instructions are included in this lab–Including complete Eclipse instructions, as well as details about the lab requirements

Subsequent labs are similar to this lab, so include fewer detailed instructions

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 34: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2420130401

Fast Track to Spring 3.x

The Eclipse Development Environment

Eclipse: Open source platform for building integrated development environments (IDEs)– Used mainly for Java development– Can be flexibly extended via plugins to add capabilities– http://www.eclipse.org is the main website

This lab includes detailed instructions on using Eclipse– Starting it, creating and configuring projects, etc.

Other labs include fewer Eclipse details - they may just say build/run as previously– Just use the same procedures to build/run as in this lab– Refer back to these lab instructions as needed

Lab

The Eclipse source base was originally developed by IBM– It was released by IBM into open source– IBM's RAD (and previously its WSAD) environment is built on top of Eclipse

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 35: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2520130401

Fast Track to Spring 3.x

Launch Eclipse

Tasks to PerformLaunch eclipse: Go to c:\eclipse and run eclipse.exe– A dialog box appears prompting for workbench location (below left)– Set the workbench location to C:\StudentWork\Spring\workspace– If a different default Workbench location is set, change it– Click OK– Close the Welcome screen: Click the X on its tab (below right)

Lab

If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly– You can put a shortcut to this executable on your desktop

You can also have your lab workspace in a different location– Again, just adjust the lab instructions as required

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 36: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2620130401

Fast Track to Spring 3.x

Workbench and Java Perspective

Tasks to PerformYou should be in a Java EE perspective *Open a Java Perspective: Click the Perspective icon at the top right of the Workbench, and select Java (see below left)– Close the Java EE perspective by right clicking its icon, and

selecting close (see below right)Unclutter the Java Perspective by closing some views– Close the Task List, Outline and Hierarchy views (click on the X)– Open the Navigator View (Window | Show View | Navigator)

Lab

The Eclipse Java EE version opens in the Java EE perspective by default– Other versions may open in a different perspective– If you're already in a Java perspective, you don't need to switch perspectives, and there is nothing

for you to do– Note that you'll need the Eclipse Java EE version for the Web and Security labs

To save a our "uncluttered" perspective as the default Java perspective go to– Window | Save Perspective As | Java

You can reset the perspective to its defaults via– Window | Reset Perspective

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 37: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2720130401

Fast Track to Spring 3.x

The Java Perspective Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 38: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2820130401

Fast Track to Spring 3.x

Create User Libraries

We'll need to include a number of Spring jars in our classpath– We include the Spring jars from the Spring distribution in the setup– We also supply other external dependencies in a separate folder– We'll set these up as a user library for ease of use

Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries– Click New… , in the next dialog, call the library Spring, and press OK– Click the Add External JARs… button, browse to StudentWork\Spring\SpringLibraries, select all the jars in that folder, and

click OK (see notes)– Select the Spring library again, click Add External JARs…, browse to

StudentWork\Spring\SpringDependencies, add in all jars in that folderCreates a library with the Spring distribution and dependency jars– We'll use it to configure the project build path

Lab

financial info

We include all the Spring jars from the Spring distribution in our setup– This is for ease of use - the Spring distribution includes a lot of extraneous jars (src and

javadoc) mixed in with the standard jars– This can be confusing when starting out, so we just supply them separately

We supply all needed dependencies in the SpringDependencies folder– These were figured out by using Maven and seeing what dependencies were added to the

project– In this folder, we supply all the external dependencies for all the labs– This is quite a bit more than is needed for this lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 39: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 2920130401

Fast Track to Spring 3.x

Create a Project for our Application

Tasks to PerformCreate a Java Project *– Call the project Lab01.1– Eclipse will then automatically set

the project folder to Lab01.1• This folder already exists in the

workspace• It contains a Java project laid out

for Eclipse– Click Next

– This will bring you to a dialog where you can set the Java Settings for the project

Lab

To create a new Java Project, use the menuitem– File| New | Java Project

There are many other ways to create a project– You can use the new icon on the left hand side of the toolbar, as shown above

You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a new Lab directory

– This happens several times in the course, and you'll need to create a new project each time

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 40: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-10 LearningPatterns Inc. All rights reserved. 3020130401

Fast Track to Spring 3.x

Add the Spring Library to the ClassPath

Tasks to PerformIn the Java Settings dialog, click the Libraries tab *– Click the Add Library button, and in the dialog that comes up,

select User Library then click Next– Check off Spring, then click Finish in all open dialogs *

Lab

If you forget to add the library in this step, you can always add it later as follows– Right click on the project, select Properties, then select Java Build Path– Go to the Libraries tab, and add in the Spring library as described above

When the project is created, Eclipse will attempt to compile all the Java source– This will lead to warnings about unused imports, variables, etc.– You can just ignore these – most of them are because the files we give you are just skeletons, and

not complete.– If you want, you can shut these warnings off as follows:

Window | Preferences | Java | Compiler | Errors/Warnings– Go to the "Unnecessary Code" section, and change the settings for "Unused import", "Unused

local or private member", and "Local variable is never read" to "Ignore"

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 41: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3120130401

Fast Track to Spring 3.x

Running the Lab

Tasks to PerformWe will use Eclipse to run a skeleton program we supply in TeachMeSpring.javaAfter a clean build (one that is error-free, but not necessarily warning-free), do the following– In the Package Explorer pane,

right click on TeachMeSpring.java(in package com.javatunes.teach under the src folder)

– Select:Run As -> Java Application

– This will automatically find the main method in TeachMeSpringand run it for you

Lab

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 42: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3220130401

Fast Track to Spring 3.x

Program Output

You should see output in the Eclipse Console view showing the results of running the program– Similar to that shown below– If you see any exceptions, then you have a problem somewhere

Note: You will follow similar procedures whenever you have a Java program to run in the labs– The only thing that may change is the program class that you'll

need to right click on to run

Lab

STOP

Lab 1.1: Setting Up the Environment

Evaluation Copy

Page 43: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3320130401

Fast Track to Spring 3.x

Spring Introduction

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 44: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3420130401

Fast Track to Spring 3.x

Managing Beans

Managing application objects is a core Spring capability

These managed objects are called beans– Just a POJO (Plain Old Java Object) – Bean is a common name (e.g. JavaBeans and EJB)

The Spring container manages objects– Often called the Dependency Injection (DI) or Inversion of

Control (IoC) container– Configuration metadata is used by the container to instantiate,

configure, and assemble your beans– Generally supplied in simple XML format

You write a configuration with bean definitions and dependencies– The container does the work of managing the beans

Spring will create and initialize bean instances based on your configuration data– You can then request those instances from the Spring container by name– We'll see how this works soon

We'll cover the Spring container, and the principles behind it, in more detail later– For now, we will just describe some of its basic capabilities

Spring 2.x added a number of Java 5 annotations that can be used, and Spring 3 added the ability to write the configuration using Java

– We'll cover these laterConfiguration metadata can also be provided in the Java properties format, or even provided programmatically (using Spring's public API)

– These are generally more cumbersome to use, and we won't cover them in this course– The vast majority of Spring users use the XML format– In fact, the Spring IoC container is totally decoupled from the external form of the metadata– It has its own internal format which it uses to store this information

Session 1: Introduction to Spring

Evaluation Copy

Page 45: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3520130401

Fast Track to Spring 3.x

A Basic Spring Application

Session 1: Introduction to Spring

Evaluation Copy

Page 46: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3620130401

Fast Track to Spring 3.x

Some Bean Classes

Assume the following types (your business objects)– Teacher interface defining our functionality– JavaInstructor: Concrete class, implementing Teacher– Note: Spring strongly advocates programming to interfaces

(see notes)

Let's look at how to manage instances of our types with Springpackage com.javatunes.teach;public interface Teacher {

public void teach();}

package com.javatunes.teach;public class JavaInstructor implements Teacher {

public void teach() {System.out.println("BeanFactories are way cool");

}}

Programming to interfaces provides many advantages by decoupling your code from concrete implementation classes

– This is not a concept unique to Spring– Many design patterns are based on the decoupling gained by programming to an interface– We'll soon see how the Spring framework makes these advantages even more usable and

powerful by helping manage the dependencies that have been abstracted using interfaces

Session 1: Introduction to Spring

Evaluation Copy

Page 47: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3720130401

Fast Track to Spring 3.x

Configuration Metadata

A Spring configuration contains bean definitions– And information about your beans (the metadata)– Bean definitions correspond to actual objects in your app that the

Spring container will manage– Typically - many bean definitions and dependencies

Beans are configured with a top level <beans> element– It contains namespace declarations and <bean> elements as

shown in the applicationContext.xml file below

<?xml version="1.0" encoding="UTF-8"?>

<!-- The beans namespace is the default one for the document --><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"/>

</beans>

applicationContext.xml is a fairly standard name for the Spring config file, but you can name it anything that you wantSpring 2.0 and later provided an XML Schema for the XML configuration file

– The examples and lab setup files have the necessary XML namespace information in them to refer to the Spring XML Schema properly

– This is standard XML usage, and we don't go into the details here of how to use an XML Schema– Refer to an XML reference if you need more detail on this– The XML Schema is the recommended way to use Spring, and we'll use it in this course

Typically you'll configure beans such as– Service layer objects, DAO objects, Hibernate session factories, JMS queue references

Some BeanFactory implementations also permit the registration of existing objects that have been created outside the factory (by user code)The schemaLocation property shown in the slide is for Spring 3.1 - for earlier versions of Spring, you would use the appropriate spring-beans-n.n.xsd

– e.g. For Spring 3.0, use spring-beans-3.0.xsd - there is very little difference between them

Session 1: Introduction to Spring

Evaluation Copy

Page 48: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3820130401

Fast Track to Spring 3.x

Declaring Beans

Each bean definition must specify a package-qualified class name– Usually the bean implementation class (i.e. the class that the

container will instantiate)– In our example, the class attribute, specifies the implementation

as com.javatunes.teach.JavaInstructor

In general, a bean identifier (or name) is also specified– In our example, the id attribute, specifies the identifier as springGuru• It is a label for the bean – both in code and the config file

– A bean can have multiple names (or aliases)– Generally, bean names use camelCase for bean names (e.g.

springGuru)

There are more sophisticated ways to create beans, for example with a factory class, in which case the class name may not be the actual implementation classIf you don't specify a bean name, the container will generate a unique name for the bean

– This can be useful in some more sophisticated scenariosThe springGuru name follows the same convention as Java instance field names

– Bean names start with a lowercase letter, and are camel cased from then onBean names must be unique within the container the bean is hosted inUsually a bean will have a single name

– If it has multiple names, these are considered aliasesThe id attribute must follow the standard XML rules for ids

– There is a limited set of characters that are allowed for XML idsThe name attribute can also be used to specify (multiple) names

– You can have a value that specifies multiple bean ids separated by a comma, semicolon, or whitespace

– If there is no id attribute, the first name becomes the identifier, the rest are aliases– You may use the id and name attributes at the same time

Session 1: Introduction to Spring

Evaluation Copy

Page 49: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 3920130401

Fast Track to Spring 3.x

The Spring Container

Spring container instantiates/configures application objects– Provides a configuration mechanism for managing objects– And resolves object dependencies based on configuration

org.springframework.context.ApplicationContext– Core API to access the Spring container in your code– Multiple implementations provided for flexibility, e.g.– ClassPathXmlApplicationContext: Commonly used

implementation that loads resources from the class path

ApplicationContext extends interface org.springframework.beans.factory.BeanFactory– Defines many core methods, but usually not used directly– ApplicationContext is the recommended API choice

Session 1: Introduction to Spring

Evaluation Copy

Page 50: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4020130401

Fast Track to Spring 3.x

Working With Spring

High level scenario for using Spring includes the following:

Create Spring configuration data for your beans– e.g. In an XML file like applicationContext.xml– Or via annotations in code (covered later)– The "cookbook" telling Spring how to create objects

Initialize Spring container, create access point, e.g.– Create an application context instance that reads config data

• It will initialize the beans in the config file– Use the context instance to access beans

Retrieve beans via the context and use them– e.g. use getBean() to look up a bean by name– getBean() is part of BeanFactory/ApplicationContext API

There are many, many usage scenarios for Spring– And many, many different alternatives for each scenario– Spring is very large, and has a lot of flexibility and capability

In this initial introduction we show you one straightforward way of using Spring– We will gradually introduce more capabilities throughout the course

Session 1: Introduction to Spring

Evaluation Copy

Page 51: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4120130401

Fast Track to Spring 3.x

A Simple Spring Example

The code below provides a simple Spring example– Based on applicationContext.xml seen earlier– Instantiates a ClassPathXmlApplicationContext to read

applicationContext.xml from the classpath to create the spring container– Looks up the springGuru bean from the container and uses it– Closes the context (destroying all beans) *

package com.javatunes.teach;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TeachMeSpring {public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

// Note that getBean uses Java generics (no casting needed)Teacher teacher = ctx.getBean("springGuru", Teacher.class);teacher.teach(); // Use our beanctx.close(); // Close the context

}}

ClassPathXmlApplicationContext(String) loads the named file from the classpath– Uses Spring-based resource classes (org.springframework.core.io.Resource

implementations) to access the file– The resource classes abstract access to resources - often used by other classes to access data– ClassPathResource is a concrete implementation that allows you to easily access resources

on the classpath, e.g. Resource resource = new ClassPathResource("applicationContext.xml");

– This is how ClassPathXmlApplicationContext accesses its resourcesThe context implementations uses Spring resources to locate the configuration files

– The Resource interface allows you to flexibly specify paths to resources as resource strings– These are then mapped by a particular implementation to the actual resource, for example a file

on a file system or from the Java classpathA bean definition can be seen as a recipe for creating one or more actual objects

– The container looks at the recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object

Closing the context reclaims all the resources and does any needed cleanup– Good practice in standalone applications, even in a small program like this which is terminating

Session 1: Introduction to Spring

Evaluation Copy

Page 52: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4220130401

Fast Track to Spring 3.x

Why Bother?

The example looks like a lot of work to create a single object !

Main benefit: We've decoupled our code from a dependency on the implementation class JavaInstructor– Our code does not need to know about JavaInstructor– We just know about the functionality we need

• i.e. The Teacher interface (which JavaInstructor implements)– We can use any conforming implementation in our configuration

• Our client code will not change– This can be very useful for complex systems

We'll soon see additional capabilities that make Spring useful

In this simple example, it looks like we've done quite a bit of work to instantiate a single instance of a single class

– What is the benefit?

The decoupling we've achieved seems like a simple thing, but it has a lot of benefits, especially when maintaining large systems

– We'll see how useful it can be when we explore more of the capabilities

Session 1: Introduction to Spring

Evaluation Copy

Page 53: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Some BeanFactory/ApplicationContext API

boolean containsBean(String): returns true if BeanFactorycontains a bean definition or instance with the given name<T> T getBean(String, Class<T> requiredType): Returns a bean instance, registered under the given name– Spring 3 style using Java generics (see notes) and is preferredObject getBean(String): Old style – non generics version– Requires cast

Class<?> getType(String name): Returns the Class of the bean with the given nameboolean isSingleton(String): Determines whether or not the named bean is a singletonString[] getAliases(String): Return the aliases for the given bean name, if anyMany more methods - view the javadoc for more details

The methods shown are a part of the BeanFactory API - inherited by ApplicationContextgetBean(String, Class) returns either a singleton (shared) instance, or newly created bean– NoSuchBeanDefinitionException thrown if the bean can't be found– BeansException thrown if an exception occurred while instantiating/preparing the bean– BeanNotOfRequiredTypeException thrown if the bean is not of the required type

Object getBean(String) returns an object – which is then cast to the required type– The newer getBean(String,Class) method is generally preferred.

getType(String) throws NoSuchBeanDefinitionException if the bean can't be foundisSingleton(String) throws NoSuchBeanDefinitionException if bean can't be foundThe method <T> T getBean(String, Class<T> requiredType) may look strange

– The first <T> in the return type simply indicates that this is a generic method, parameterized by the type parameter <T>

– The T return value indicates that the return type is generic (that is, it will take on different types based on the <T> parameter)

– The Class<T> argument indicates that when you call the method, you pass in the class which specifies what type <T> actually is in that call

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4320130401

Fast Track to Spring 3.x Session 1: Introduction to Spring

Evaluation Copy

Page 54: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4420130401

Fast Track to Spring 3.x

Lab 1.2 – Hello Spring World

Lab 1.2: Hello Spring World

Evaluation Copy

Page 55: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4520130401

Fast Track to Spring 3.x

Lab 1.2 – Hello Spring World

Overview: In this lab, we will create and use a Spring context to access a bean instance– The end goal is to build a complete (and simple) Spring

application and run it– This lab uses the JavaInstructor, Teacher, and TeachMeSpring types shown previously in the student manual

Objectives: – Become familiar with the different parts of a basic Spring

program– Write and run a simple Spring application

Builds on previous labs: 1.1

Approximate Time: 20-30 minutes

Lab

The purpose of this lab is to become familiar with the different parts of a Spring application– Accordingly, the program is as simple as we can make it– It mirrors the code already shown in the previous section

In later labs, we'll work with more complex applications

Lab 1.2: Hello Spring World

Evaluation Copy

Page 56: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4620130401

Fast Track to Spring 3.x

Writing and Configuring a Bean in Spring

Tasks to PerformContinue to work in the Lab01.1 projectOpen up the JavaInstructor.java fileThe class is in the com.javatunes.teach package, under srcMake sure JavaInstructor implements the Teacher interface– Remember that we code to interfaces to decouple us from a

specific implementationOpen up the src/applicationContext.xml file– Click the Source tab to edit it– Finish up the declaration of the <bean> element by declaring:

• An id of springGuru• A class of com.javatunes.teach.JavaInstructor

Lab

There are two other files in the src tree that we will use in the next lab– InfoSource.java and SpringCourseBook.java– Ignore these for now

Lab 1.2: Hello Spring World

Evaluation Copy

Page 57: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4720130401

Fast Track to Spring 3.x

Using a Bean in a Program

Tasks to PerformOpen up TeachMeSpring.java, look for the TODO comments, and add in the following code– First, create a ClassPathXmlApplicationContext to read

applicationContext.xml– Next, look up the springGuru bean from the context– Call teach() on the springGuru bean– Finally, call close() on the context

Make sure you have no compilation errors in your code

Run the TeachMeSpring program again– Run the same way as in previous labs– You should see the output from the teach() method

You've successfully configured and used a bean with Spring– Congratulations !

Lab

Lab 1.2: Hello Spring World

Evaluation Copy

Page 58: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4820130401

Fast Track to Spring 3.x

Logging and Additional Things (Optional)

We've provided a log4j.properties file in src– This configures some of the logging that Spring will do– You can reduce the logging output by opening this file, and

changing the INFO to WARN at the top line of the file:log4j.rootLogger=WARN, stdout

– You can increase the logging by using DEBUG instead

Other things to try– Try looking up the bean by a different name – what happens?– Try casting the bean you look up to a JavaInstructor

instead of a Teacher• Does this work? • Is it a good idea? (see notes)

– Change your code back to your original solution before going on STOP

Spring has logging built into it– It uses commons-logging by default, which will detect the log4j jar file and use that if it is on the

classpath– You can see the logging by properly configuring it, as we do in the log4j.properties file– The details of log4j are beyond the scope of this course

Casting the bean you look up to a JavaInstructor will work– These are POJOs, and the actual type is JavaInstructor– It's not a good idea though, because you are defeating the purpose of decoupling your code from

the actual implementation type

Lab 1.2: Hello Spring World

Evaluation Copy

Page 59: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 4920130401

Fast Track to Spring 3.x

Dependencies and Dependency Injection

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Evaluation Copy

Page 60: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5020130401

Fast Track to Spring 3.x

Dependencies Between Objects

Different objects work together in an OO application– e.g., Object A directly uses Object B to accomplish a goal– Object A depends on Object B

Direct dependencies can lead to unwanted traits– Rigidity: Hard to make changes - they affect many other parts of

the system– Fragility: Changes cause unexpected failures in other system

areas– Immobility: Hard to reuse functionality elsewhere - modules

can't be disentangled

We'll show a direct dependency example, then show an alternative approach using Dependency Inversion

In straightforward applications, Object A will often just create an instance of Object B and use it– Object A is highly coupled to, and directly dependent on, Object B

Session 1: Introduction to Spring

Evaluation Copy

Page 61: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5120130401

Fast Track to Spring 3.x

Example of a Direct Dependency

Assume JavaInstructor uses SpringCourseBook– Below, JavaInstructor creates a SpringCourseBook

instance directly– JavaInstructor depends on the lower level module details– If the data source changes - e.g. to a SpringWiki, then JavaInstructor code must change (see notes)

public class JavaInstructor implements Teacher {SpringCourseBook springBook = new SpringCourseBook();public void teach() {

System.out.println(springBook.getData());}

}

public class SpringCourseBook { // package statements not shown *public String getData() {

return "Dependencies are not so cool";}

}

Assume that all the classes in the examples in this session are in the com.javatunes.teachpackage

– We'll be leaving out all the package statements in the Java code examples for brevityAssume we want to get our information from a class called SpringWiki

– Not shown, but assume it has a getData() methodIn that case, JavaInstructor might need to be changed to something like that below

public class JavaInstructor implements Teacher {

SpringWiki springWiki = new SpringWiki();

public void teach() {

System.out.println(springWiki.getData());

}

}

– This is not such a big deal if you have to change it in one place– But imagine if you had to change it in 100 places, or 10,000 places

Session 1: Introduction to Spring

Evaluation Copy

Page 62: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5220130401

Fast Track to Spring 3.x

Dependency Inversion Principal

High level or low level modules should should depend upon abstractions and not upon each other– Use abstractions, e.g. interfaces, that all modules depend on– High level modules are written in terms of abstractions (the

interfaces), and not directly in terms of low level modules– Dependencies exist, but not exposed in implementation classes

Using this design strategy has a number of advantages:

– Facilitates less coupled components• With a high degree of separation of responsibilities

– Produces greater flexibility• Implementations can be swapped without affecting other modules

– Facilitates reuse of components• They're less coupled to other parts of an application

Dependency Inversion is not a new idea– The idea of "Programming to Interfaces" has been around since long before Java– It has been used in non-OO languages also, for example the stdio module in the C programming

language abstracted away the details of the actual devices doing the output

Many people don't use this design in building applications– Even though we know of good design principals, there is no way to make sure people use them

We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use

We talk of modules here, which in Java are basically reflected as dependencies between different classes

Session 1: Introduction to Spring

Evaluation Copy

Page 63: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5320130401

Fast Track to Spring 3.x

Example of Dependency Inversion

Both JavaInstructor and SpringCourseBook depend on InfoSource (an interface) – neither depend on the other

public class JavaInstructor implements Teacher {private InfoSource info;public void setInfo (InfoSource infoIn) {

info=infoIn;}public void teach() {

System.out.println(info.getData());}

}

public class SpringCourseBook implements InfoSource {public String getData() {

return "Dependencies are not so cool";}

}

public interface InfoSource {public String getData();

}

In the code example, we can see that JavaInstructor knows nothing about SpringCourseBook– Instead, it depends on the InfoSource interface (the abstraction)– When JavaInstructor is created, it is initialized with an instance of some InfoSource

implementation– However, it doesn't know any details of this implementation, and doesn't even know its exact

type

SpringCourseBook likewise depends on the abstraction (it implements the InfoSource interface)– The abstraction (the interface) is the common language that lets the different part of the system

work together with depending directly on each other

Session 1: Introduction to Spring

Evaluation Copy

Page 64: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5420130401

Fast Track to Spring 3.x

Example of Dependency Inversion

Below, JavaInstructor is initialized with a SpringCourseBook instance (that implements InfoSource)

– JavaInstructor only sees this as the InfoSource type– We could initialize JavaInstructor with any type that

implemented InfoSource – e.g. a SpringWiki– We've decoupled the modules, and made them more flexible and

easier to use, reuse, and maintain

public class TeachMeSpring {

public static void main(String[] args) {SpringCourseBook springBook = new SpringCourseBook();JavaInstructor myInstructor = new JavaInstructor();myInstructor.setInfo(springBook);myInstructor.teach();

}}

In the example above, we are still creating SpringCourseBook in a fairly straightforward way– This exposes the actual implementation class of the lower level module (SpringCourseBook)

in our TeachMeSpring code– There are other, more sophisticated, ways to create these lower level modules– For example, we could use factories of some sort to more completely abstract which

InfoSource is being used– We will soon show how Spring can do this for you

Whenever you have modules depending on one another, something has to know about the implementation details

– Even if it's abstracted through multiple layers, there is still a layer somewhere which creates the instance of the actual implementation

– The goal is to do this in a way that makes your code easier to write, reuse, and maintain

We'll see how Spring deals with this soon

Session 1: Introduction to Spring

Evaluation Copy

Page 65: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5520130401

Fast Track to Spring 3.x

Dependency Injection (DI) in Spring

With Dependency Injection, Spring lets you abstract dependencies even more– The Spring container can initialize and inject dependencies into

a bean• Via constructors, properties in the bean, or arguments to a factory

method

Dependencies are defined in the Spring configuration– The Spring container uses these dependency definitions to

initialize the bean– No need to explicitly initialize dependencies in your code

Your bean classes are normal POJO classes– You only need appropriate setter methods or constructors

needed to initialize the dependencies– There is nothing else special about the bean classes

Dependency injection is a fancy way of saying that the container will initialize all the dependencies in the bean when the bean is created

– The bean has to be a bean whose lifecycle is managed by the container

Session 1: Introduction to Spring

Evaluation Copy

Page 66: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5620130401

Fast Track to Spring 3.x

Dependency Injection Configuration

The Spring configuration below uses DI

– Declares two beans: springBook and springGuru– <property name="info" ref="springBook"/> tells the

container to initialize the info property of springGuru• Using the instance of SpringCourseBook defined above it

– Uses setter injection - calling setInfo() on springGuru– You don't need to write any code for the injection to happen

<?xml version="1.0" encoding="UTF-8"?>

<beans … > <!-- Namespace declarations omitted -->

<bean id="springBook" class="com.javatunes.teach.SpringCourseBook"/>

<bean id="springGuru" class="com.javatunes.teach.JavaInstructor"><property name="info" ref="springBook"/>

</bean>

</beans>

The container first creates an instance of SpringCourseBook, with the id springBookThe container next creates an instance of JavaInstructor using the no-arg constructor

– To accomplish the DI, the container calls the setInfo method, passing in the instance of SpringCourseBook that it had created

– The result is a fully initialized JavaInstructor instanceThe <property> element tells the container to use setter injection to initialize the dependency

– Setter injection uses the standard setter methods on your bean– It follows the standard property naming conventions, so if the property is named info, it will

call the setInfo method to initialize the dependency– There are other ways of initializing the dependency, such as constructor injection, that we'll see

laterThe bean reference can also be declared using a nested <ref> element as shown below<property name="info"><ref bean="springBook"/></property>

– Generally, the ref attribute shown in the slide is easier to use and understand– You can use the nested element if for some reason it is clearer to express it this way than as an

attribute (this is also provided for backwards compatibility with earlier Spring releases)

Session 1: Introduction to Spring

Evaluation Copy

Page 67: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5720130401

Fast Track to Spring 3.x

Dependency Injection Example

The example below shows how to use our beans with Spring– Our main code is decoupled from JavaInstructor - it is

written in terms of the Teacher interface– JavaInstructor, is totally decoupled from the concrete class SpringCourseBook, it's written in terms of InfoSource

– The JavaInstructor instance's info property is injected with a SpringCourseBook instance by the Spring container• This is transparent to all your code

// imports not shownpublic class TeachMeSpring {

public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new

ClassPathXmlApplicationContext("applicationContext.xml");Teacher teacher = ctx.getBean("springGuru", Teacher.class);teacher.teach();

}}

Note that your SpringCourseBook and JavaInstructor class definitions didn't need to change to use DI

– Of course, they had to support the design principle of Dependency Inversion, which we had already done

– Once this was done, we didn't need any changes or additional code to support DINote also that there is nothing in your TeachMeSpring code which shows that JavaInstructordepends on SpringCourseBook

– This is defined in your configuration, and handled for you by the containerNote that the no-arg constructor is present by default in JavaInstructor since we haven't defined any constructors at all

– If we defined constructors, and still wanted to use only setter injection, as for the configuration file in this example, we would have to include a no-arg constructor

– We'll take a look at constructor injection, which allows us to use constructor arguments, a little later

Session 1: Introduction to Spring

Evaluation Copy

Page 68: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5820130401

Fast Track to Spring 3.x

Advantages of Dependency Injection

DI reduces coupling between modules in your code– Coupling is basically a measure of the dependencies

We've seen this reduction in two ways in our example:– JavaInstructor is not coupled to SpringCourseBook– TeachMeSpring is not coupled to JavaInstructor or SpringCourseBook

The dependencies are still there but not in the code– Dependencies are moved to the spring configuration– They're injected into beans without your needing to write code– Commonly referred to as wiring beans together

This leads to more flexible code that is easier to maintain– At a cost – using Spring, and maintaining the spring configuration

Coupling is the measure of how much a module of code relies on other modules– Loosely coupled code is generally considered better code

Consider some of the following scenarios, and how DI makes them easier– Testing your code with testing framework such as JUnit can be much easier with DI – you can

configure the application to use mock objects wherever you want – without changing your code at all

– Testing different versions of classes can be done just by changing the configuration metadata– In fact, any implementation class that implements the particular interfaces being used can be

swapped into your program simply by changing the configuration informationThere is debate about how worthwhile DI and frameworks like Spring are

– However, the principles that it is based on that lead to loose coupling are widely accepted– Spring simply makes it easier to apply these principles– The effort required to adopt and use Spring is not trivial, but for larger projects the initial cost

of adopting Spring can be well worth it

Session 1: Introduction to Spring

Evaluation Copy

Page 69: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 5920130401

Fast Track to Spring 3.x

Dependency Injection Reduces Coupling

The simplest case, JavaInstructor coupled to SpringCourseBook

JavaInstructor coupled to InfoSource only– TeachMeSpring coupled to JavaInstructor and SpringCourseBook

Using DI - TeachMeSpringonly coupled to Teacher– JavaInstructor only

coupled to InfoSource

JavaInstructor SpringCourseBook

InfoSource<<interface>>

creates

JavaInstructor

SpringCourseBookTeachMeSpringimplements

creates

InfoSource<<interface>>

TeachMeSpring

Teacher<<interface>> JavaInstructor

implements

looks up

ApplicationContext

injects

In the slide, we show diagrams of the three different ways we structured our code in the earlier slides

In the DI version, the couplings are ONLY to interfaces– This is much better than being coupled to actual implementation classes– It increases flexibility, testability, and ease of maintenance

Session 1: Introduction to Spring

Evaluation Copy

Page 70: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6020130401

Fast Track to Spring 3.x

Lab 1.3 – Dependency Injection

Lab 1.3: Dependency Injection

Evaluation Copy

Page 71: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6120130401

Fast Track to Spring 3.x

Lab 1.3 – Dependency Injection

Overview: In this lab, we'll work with Spring's DI capabilities– We will add a property (a dependency on another bean) to the JavaInstructor class, and initialize it using Spring DI

– The main program will not change at all– Again, the program is kept very simple so the concepts will be

clear

Objectives: – Become familiar with Spring DI, and use it in a program

Builds on previous labs: 1.2

Approximate Time: 20-30 minutes

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 72: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6220130401

Fast Track to Spring 3.x

Writing and Configuring a Bean in Spring

Tasks to PerformContinue to work in the Lab01.1 project

Open up SpringCourseBook for editing– Make sure that SpringCourseBook implements the InfoSource interface

Open up JavaInstructor for editing– Add in a property called info, of type InfoSource– You'll need an instance field of type InfoSource, as well as a

getter/setter method for this field– Modify the teach() method to print out the data from the info

properties getData() method

We won't initialize the info property – that will be done with DI

Lab

All the classes we're working with are in the com.javatunes.teach package

Lab 1.3: Dependency Injection

Evaluation Copy

Page 73: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6320130401

Fast Track to Spring 3.x

Using a Bean in a Program

Tasks to PerformOpen up the src/applicationContext.xml file– Add in a new bean element for SpringCourseBook

• Give it an id of springBook– Modify the <bean> element for springGuru by initializing its info property with a <property> element• Use the springBook bean to initialize the info property

Run the program as before– The output should now be whatever data the SpringCourseBook returns

– The main program doesn't change at all – the JavaInstructordependency on SpringCourseBook is completely hidden

– JavaInstructor is also decoupled from SpringCourseBook

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 74: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6420130401

Fast Track to Spring 3.x

Additional Things to Try (Optional)

In applicationContext.xml, try leaving out the initialization of the springGuru bean's info property– Run your program– What happens? Why?

Change your code back to your original solution before going on

STOP

Lab

Lab 1.3: Dependency Injection

Evaluation Copy

Page 75: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6520130401

Fast Track to Spring 3.x

Review Questions

What is Spring?

How does Spring help you to build enterprise applications?

What is Dependency Injection, and how does it work in Spring

Session 1: Introduction to Spring

Evaluation Copy

Page 76: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6620130401

Fast Track to Spring 3.x

Lesson Summary

Spring is a lightweight framework for building enterprise applications whose capabilities include:– Dependency Injection– Persistence support (DAO and ORM)– AOP capabilities– Integration with standard Web technologies– An MVC based Web package

Spring helps build complex enterprise applications– Provides a non-intrusive, lightweight solution for managing

complex dependencies between Java objects– Supplies many of the important capabilities of Java EE in a less

complex and lighter weight manner

Session 1: Introduction to Spring

Evaluation Copy

Page 77: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 6720130401

Fast Track to Spring 3.x

Lesson Summary

Spring supports loose coupling between components– Promotes technique of coding to interfaces, rather than

concrete implementation classes– This by itself is an important design technique,

Provides support for initialization of beans and their dependencies through configuration– Can be done using XML configuration files

Dependency Injection is used by the Spring container to inject bean dependencies based on configuration data– Allows complete decoupling of your code from concrete

implementation types

Session 1: Introduction to Spring

Evaluation Copy

Page 78: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31120130401

Fast Track to Spring 3.x and Spring MVC/REST

Session 6: Web Applications with Spring MVC

Integration with Java EESpring MVC Basics

Forms and Command Objects

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 79: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31220130401

Fast Track to Spring 3.x and Spring MVC/REST

Lesson Objectives

Integrate the Spring container with regular Java Web Applications (first section)

Understand what Spring MVC is, its goals, and its architecture– Learn how to configure the Spring MVC DispatcherServlet– Use Command Controllers to handler requests– Use View Resolvers to map logical names to actual resources (e.g.

JSP)– Use Spring MVC's support for forms including command classes and

form controllers– Understand how Spring uses Handler Mappings to map URLs to

controllers

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 80: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31320130401

Fast Track to Spring 3.x and Spring MVC/REST

Integration with Java EE

Integration with Java EESpring MVC Basics

Forms and Command ObjectsAdditional Details

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 81: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31420130401

Fast Track to Spring 3.x and Spring MVC/REST

Spring and Java EE

Java EE (Enterprise Edition): Standard Java architecture for building scalable, distributed, reliable, Enterprise apps– Enterprise Edition basically means "Server Side" Java

Spring can complement or replace many parts of Java EE– Often useful to integrate existing web apps with Spring– Fairly easy to use Spring beans and DI with Java EE Web apps– We'll look at this first - it is used for Spring MVC integration also

We'll look at Spring MVC after this– Powerful web framework to build complex web apps more easily

Java EE applications normally have many components– Spring can replace or augment some of the functionality to produce code that is easier to use and

maintain

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 82: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31520130401

Fast Track to Spring 3.x and Spring MVC/REST

Overview of Java EE Web Applications

Standard structure defined in Java EE– A collection of Servlets, JavaServer Pages (JSP), & other files– Most frequently collected inside of a Web Archive (WAR) file

• The standard Java EE web app packaging

Middleware (J2EE space)Client Backend

Browser

Database

Web Server

EJB

Web Application

Servlets/JSP/Spring

HTTP

EIS resources

RMI

JDBC

JDBC

Rich ClientRMI

A jar file is basically a zip file with added information in it– It is compatible with the zip format, and jar files can be manipulated using most zip tools– There is also a utility program that comes with Java to create and work with jar files

The WAR file can be deployed directly to servers that support web applications (such as Tomcat or WebSphere)

Every web app has a standard directory structure – Which generally includes an XML configuration file - web.xml– We'll assume that you are already somewhat familiar with this structure

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 83: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31620130401

Fast Track to Spring 3.x and Spring MVC/REST

Web Application Structure

<Web application base directory>[static content files: HTML, forms, images, etc.][dynamic content: e.g. JSP][other content directories]WEB-INF

web.xmlclasses

[.class files: servlets and others]lib

[JAR files]

Web application configuration file

Java web apps are organized in the standard structure below

The WEB-INF directory is just a normal directory of this name– It’s an unusual name, but don’t be confused by that– It was chosen so its name is unlikely to conflict with a name in your web app structure– It’s still just a normal directory

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 84: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31720130401

Fast Track to Spring 3.x and Spring MVC/REST

Web Application Components

Servlets: Java components that run on the server– Servlets run in response to client requests– Defined by extending class javax.servlet.HttpServlet

and overriding doGet()/doPost()

JSP: JavaServer Page - contains dynamic and static content– Template Data consists of regular text, HTML, XML ...– Dynamic Data is generated anew for each request - e.g from

custom tags in the JSP

web.xml: Deployment descriptor for web app– Contains configuration information for the web app– For example, the servlets and their mappings

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 85: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31820130401

Fast Track to Spring 3.x and Spring MVC/REST

ApplicationContext and Java Web Apps

Spring's WebApplicationContext provides integration with the Java Web container– This is a context tailored for Web app use

Spring's ContextLoaderListener makes loading the context easy– Automatically loads the context when the web app is deployed– You can define the Spring configuration file locations using a <context-param> element in web.xml

WebApplicationContextUtils class is used to access the context in your web app code– Via the static method getWebApplicationContext()– If using standard Java Web apps– The following slides shows examples of doing this

We'll see when we discuss Spring MVC, there can be multiple application contexts in a Web application

– The one started up by the ContextLoaderListener is the root of all these application contexts

– It is available to all other application contexts

There are other ways of getting the application context besides using WebApplicationContextUtils

– However, this is the easiest and most general way

By default, ConextLoaderListener loads the configuration file from "/WEB-INF/applicationContext.xml"

– You can specify your own location using <context-param>

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 86: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 31920130401

Fast Track to Spring 3.x and Spring MVC/REST

Configuring ContextLoaderListener

The web.xml below configures the ContextLoaderListener– It specifies applicationContext.xml and inMemoryItemDAO.xml

as config files via <context-param>

<web-app ... >

<context-param> <!-- config files for ContextLoaderListener --><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml/WEB-INF/inMemoryItemDAO.xml

</param-value></context-param>

<listener> <!-- Load root application context at startup --><listener-class>org.springframework.web.context.ContextLoaderListener

</listener-class></listener>

</web-app>

If you don't specify the contextConfigLocation context parameter, the ContextLoaderListener will load a file called /WEB-INF/applicationContext.xmlOnce the context files are loaded, Spring creates a WebApplicationContext object based on the bean definitions and stores it in the ServletContext of the web application.You can also use Java-based configuration with a Web app by replacing the Web application context with a different one, as follows:

<context-param>

<param-name>contextClass</param-name>

<param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext

</param-value>

</context-param>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>com.acme.AppConfig</param-value>

</context-param>

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 87: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32020130401

Fast Track to Spring 3.x and Spring MVC/REST

Using the Application Context

Below, we retrieve the context via WebApplicationContextUtils– This is the context loaded by the ContextLoaderListener– Bean look up is the same as in non-web related code– The example assumes the same configuration and beans as in our

JavaTunes labs earlier in the course

You can see - it's very easy to use Spring with Web apps– For other frameworks, like Spring MVC, integration is even easier *

import org.springframework.web.context.support.WebApplicationContextUtils;import org.springframework.web.context.WebApplicationContext;

public class SearchServlet extends HttpServlet {public void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(

getServletContext());Catalog cat = ctx.getBean("javaTunesCatalog", Catalog.class);

}

The application context that is initialized by ContextLoaderListener is a WebApplicationContext

– This interface extends ApplicationContext, and adds Web specific functionality, including the ability to define beans in specific scopes

– For example, if you wanted to define a catalog bean in the session scope, then you could as follows

<bean id="javaTunesCatalog" class="com.javatunes.catalog.JavaTunesCatalog"scope="session">

– The Spring container will create a brand new instance of the JavaTunesCatalog bean using the 'javaTunesCatalog' bean definition for the lifetime of a single HTTP Session

– There are also request, and globalSession scopes– See the reference manual and documentation

Spring MVC uses the same context listener to integrate the Spring and Java Web containers– It does this transparently to you, and you don't have to use WebApplicationContextUtils– We'll see this soon

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 88: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32120130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.1 – Spring and the Web

Lab 6.1: Spring and the Web

Evaluation Copy

Page 89: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32220130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.1 – Spring and the Web

Overview: In this lab, we will integrate the Spring container with a regular Java Web application– We will need to set up our Web server (Tomcat)– We will then configure the ContextLoaderListener in web.xml, and use the application context in a servlet • We'll look up a Spring bean (a catalog) that's used in a JSP page

Objectives: – Configure ContextLoaderListener– Use an application context from a servlet

Builds on previous labs: none

Approximate Time: 30-40 minutes

Lab

Lab 6.1: Spring and the Web

Evaluation Copy

Page 90: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32320130401

Fast Track to Spring 3.x and Spring MVC/REST

The JavaTunes Online Store

The Web application we are creating is a small piece of the JavaTunes online music store– It displays a search form– The search form sends a

request to a servlet that does a search and forwards to a results page that displays the results

– We are working with the servlet processing the search request

– The flow for JavaTunes appears at right

The first thing we'll do is set up the environment and the Tomcat Web server

SearchServlet

searchResults.jsp

User submits the search form

Search results pagedisplayed in browser

Lab

Lab 6.1: Spring and the Web

Evaluation Copy

Page 91: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32420130401

Fast Track to Spring 3.x and Spring MVC/REST

Eclipse and Web Projects

Dynamic Web Projects used for Java Web apps in Eclipse– These contain servlets, JSP pages, and static resources (HTML)– Web-specific project properties can be establish when creating

the project– web.xml has a custom editor for ease of use

Projects are organized in the following folders– src: Contains all Java source files– WebContent: Contains all Web resources– WebContent\WEB-INF: Same as Java EE WEB-INF

• Also contains Spring configuration files, other config files– This is different from a standard Java EE Web app

• When deployed, a standard WAR is build

Lab

All visible elements in the project are not necessarily deployed with the project– e.g. the src folder is not deployed - only compiled classes– Eclipse creates a standard WAR file when it deploys the project

The src folder contains all Java source - including servlets, supporting classes, and JavaBeans– The compiled output is put in the WEB-INF\classes directory

The WebContent folder contains all Web resources - HTML files, JSP files, image files, etc.– Only content in this folder (or a sub-folder) can be accessed in the Web application

HTML and JSP pages must be correctly placed relative to the context root

– Media files, JAR files, loose class files and other resource libraries must also be correctly placedBoth the Web and Java EE views are useful for managing Web projects

– Web perspective contains HTML/JSP oriented views not in J2EE perspectiveThe web.xml file holds many settings

– Servlets to be run in project– Initial (welcome) pages and error pages – Environment values and JNDI references to resources made in servlets/JSP’s

Lab 6.1: Spring and the Web

Evaluation Copy

Page 92: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32520130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab Directory Structure

The labs in this section are structured as follows:– LabNN : Directory for Lab NN– LabNN/src/ : Java source– LabNN/WebContent/ : jsp,

HTML– LabNN/WEB-INF/: web.xml,

other config files– LabNN/WEB-INF/lib: jar files

needed by the Web app

Lab

For these labs, which are deployed in a war file to a server, the dependencies are included in the project

– Including the jars that are in the Spring library you add to the project– This is how Eclipse organizes the Dynamic Web Project– These jar files will end up in WEB-INF/lib in the war file once you deploy the Web app

• This is the standard place for them in the Java EE WAR packaging

Lab 6.1: Spring and the Web

Evaluation Copy

Page 93: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32620130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab Preparation

The root lab directory where you will do all your work is: C:\StudentWork\Spring\workspace\Lab06.1– This is a new lab directory which already exists in your workspace

Lab

Tasks to PerformClose all open files and projectsOpen the Java EE perspective, by clicking the Perspective icon at the top right of the Workbench, and select Java EE– This perspective is well suited for these labs

Lab 6.1: Spring and the Web

Evaluation Copy

Page 94: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32720130401

Fast Track to Spring 3.x and Spring MVC/REST

Creating a Server

We will use Tomcat to run our Web applications - first we need to create a server in Eclipse *

Tasks to Perform1. Go to the Servers view, right click, and select New | Server2. In the next dialog, select Apache | Tomcat V7.0 * and click Next3. In the next dialog, browse to your Tomcat install directory, click

OK, and then Finish *

Lab

Make sure that Tomcat is installed – likely in a directory such as C:\apache-tomcat-7.0.33– If its been installed in a different directory, you'll need to modify the instructions in the lab to

refer to your install directory– If it isn't installed, you'll need to download then install it– Download it from:

http://tomcat.apache.org/download-70.cgiIf you use a Tomcat version other than 7.0, then select the appropriate version in the dialog where you choose the serverEclipse for Java EE has support for deploying Web applications to a configured server

– It also has support to start and stop the servers from within EclipseIf you click Next instead of Finish in Step 3, you'll come to a dialog that lets you configure the project to run on the server

– We are going to do this slightly differently

Lab 6.1: Spring and the Web

Evaluation Copy

Page 95: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32820130401

Fast Track to Spring 3.x and Spring MVC/REST

Configure Server

We will reconfigure the deploy location for our server– This will help prevent Eclipse deploy issues we've seen (see notes)

Lab

Tasks to PerformIn Servers view, double click on the Tomcat server– The server configuration should open in the editor pane– Check the "Use Tomcat installation" choice (see below)– Save the configuration

The default integration with Tomcat deploys to a location in the workspace (under the .metadata folder)

– We've sometimes seen issues where this creates intermittent problems in deploying Web applications

– Changing the deploy location to use your actual Tomcat install folder seems to reduce or eliminate these problems

– Accordingly, we tell you how to change the deploy location to the Tomcat install folder in this slide

Lab 6.1: Spring and the Web

Evaluation Copy

Page 96: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 32920130401

Fast Track to Spring 3.x and Spring MVC/REST

Create a Web Project

Tasks to PerformCreate a new Dynamic Web project (as at right)– File | New | Dynamic Web

Project *– Call it Lab06.1 *– Make sure the Tomcat runtime

is selected and Click NextIn the next dialog, change the Context Root to javatunes (all lower case - as below)– Click Finish

Lab

There are multiple ways to create a new project:– Click on the “New Wizard” button in left side of the toolbar– Right click in the Package Explorer View, select New ...– etc.

Lab 6.1: Spring and the Web

Evaluation Copy

Page 97: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Configure Build Path

Tasks to PerformRight click on the project in Project Explorer, select Build Path |

Configure Build Path, add the Spring library as for other projectsNext, click Deployment Assembly in the left pane (for configuring

Web app deployment dependencies)– Click Apply if prompted to save modifications– Click Add | Java Build Path Entries click Next, select the Spring

library, click Finish, then OKReview the jars in the Spring library (in your Eclipse project)

– Note the jars that support the Spring/Web integration• e.g. jars from Spring like spring-web-3.2.2.RELEASE.jar, and the spring-

web-servlet jar• There are others in the dependencies we supply - e.g. the JSTL jar

Lab

We need to add the Spring library (including the web support) to our project classpath to allow the Web app to compile/run properly

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33020130401

Fast Track to Spring 3.x and Spring MVC/REST Lab 6.1: Spring and the Web

Evaluation Copy

Page 98: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33120130401

Fast Track to Spring 3.x and Spring MVC/REST

Configure ContextLoaderListener

Tasks to PerformNote: All Web content (JSP files, WEB-INF folder, …) appears in the Project Explorer pane under the WebContent folder

Open up WEB-INF\web.xml for editing– Locate the <context-param> element and add in the values for

the elements shown below:

– <param-name>: contextConfigLocation

– <param-value>:/WEB-INF/applicationContext.xml

/WEB-INF/inMemoryItemDAO.xml

– Locate the <listener> element and add in the following value for the <listener-class> element:

org.springframework.web.context.ContextLoaderListener

Lab

Lab 6.1: Spring and the Web

Evaluation Copy

Page 99: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33220130401

Fast Track to Spring 3.x and Spring MVC/REST

Finish SearchServlet

Tasks to PerformOpen com.javatunes.web.SearchSevlet for editing– Notice the Spring imports for the web context classes– Find doPost(), & initialize the WebApplicationContext by

calling the static WebApplicationContextUtils method getRequiredWebApplicationContext() (See manual slides)

– Pass in a servlet context retrieved via getServletContext()

Review the rest of the doPost() code – It uses the context to look up a Catalog– It uses the catalog to do keyword based search

• Using a keyword from a search form a web page– Search results are put on the request under the name "results"– The request is forwarded to /jsp/searchResults.jsp for display *

Lab

You can look at the jsp/header.jspf, and jsp/searchResults.jsp files also if you want– They contain the search form and the search results display page respectively– The search form contains a bunch of HTML to make it display nicely , but is basically just a

form with a single input field, as shown below:<form method='post' action='/javatunes/search'>

<input size='20' type='text' name='keyword'/><br/>

<input type='submit' name='Submit' value='Search'/>

</form>

– The SearchServlet is configured in web.xml with a url of /search, and so this form is processed by the search servlet - which puts a collection of MusicItem on the request with the name of "results"

– searchResults.jsp contains a number of JSTL tags that iterate over the results collection, displaying the data on each MusicItem in the results

Lab 6.1: Spring and the Web

Evaluation Copy

Page 100: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33320130401

Fast Track to Spring 3.x and Spring MVC/REST

Deploying an Application Lab

Tasks to PerformTo deploy to the server, right click on the Lab06.1 project, and select Run As | Run on ServerIn the next dialog box select your existing Tomcat serverAlso select Set server as project default, as we will always use this serverClick Finish

Note that running a Web app on the server will automatically start the server

We have experienced some situations where the Web application does not deploy correctly for some reasonIn these cases, the following steps sometimes correct the problem

– In the Servers view, right click on the server, select Add and Remove Projects– Remove the Lab06.1 project– Restart the server (Right click on the server, select Restart)– Add the project back into the server (Right click on the server, Add and Remove Projects, add

Lab06.1)– Restart the server again– Try browsing to your web app

Lab 6.1: Spring and the Web

Evaluation Copy

Page 101: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33420130401

Fast Track to Spring 3.x and Spring MVC/REST

Viewing the Web Application

Eclipse should open a browser for you onto the Web app– At: http://localhost:8080/javatunes

Note: Eclipse uses the system default browser, often IE, and IE can be misleading as it caches pages, and it's hard to clear the cache– If you ever feel your having browser issues, open an external browser

viewing the same URL (see notes about setting the browser in Eclipse)

Lab

Tomcat listens on port 8080 by defaultYou can also change the Web browser that Eclipse uses

– Go to the Eclipse Preferences, and navigate to General | Web Browser– Generally, your standard Web browsers will be detected – otherwise you'll need to add them– The example below uses an external Firefox browser – an external browser is easier to control in

terms of caching than the internal one, and Firefox is also easier than IE

Lab 6.1: Spring and the Web

Evaluation Copy

Page 102: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33520130401

Fast Track to Spring 3.x and Spring MVC/REST

Test Your Application

Tasks to PerformThe javatunes web app, displays a search form - so type in the letter "a" to search on and submit the form– The SearchServlet will be invoked, use your Spring beans to do the

search, and then forward to a JSP to display the results– That's it - you're using Spring in a Web application

Lab

Lab 6.1: Spring and the Web

Evaluation Copy

Page 103: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33620130401

Fast Track to Spring 3.x and Spring MVC/REST

Server Startup

You can open the Console view to see output from the server startup and web app deployment– This can be useful to look for exception stack traces– Note that server startup may take some time, especially the first

time you start the server– You can also look at the server status in the Servers view

Lab

STOP

Lab 6.1: Spring and the Web

Evaluation Copy

Page 104: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33720130401

Fast Track to Spring 3.x and Spring MVC/REST

Spring MVC Basics

Integration with Java EESpring MVC Basics

Forms and Command Objects

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 105: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33820130401

Fast Track to Spring 3.x and Spring MVC/REST

What is Spring MVC?

A Java Web app framework based on Model View Controller (MVC)– Originally created due to shortcomings of Servlets/JSP

• Current JSF (JavaServer faces) has much capability, but some are not happy with it

– If you're using Spring, Spring MVC is a viable alternative

Overall goals for Spring MVC– Simplify web app creation– Provide a strong MVC framework with clearly defined roles (controller,

command object, view resolver, etc)• Thus encouraging good architecture

– Integrate easily with the rest of Spring– Build on standard Java EE (servlets/JSP, custom tags, JavaBeans)– Flexibly integrate with additional template technologies (e.g. Velocity)

Spring MVC was introduced fairly early in the life of the JEE platform because of shortcomings in the vanilla Servlets/JSP technology, which was all that was available in J2EE at the time, as well as shortcomings in other available technologies

– The Spring Framework features its own MVC web application framework, which wasn't originally planned. The Spring developers decided to write their own web framework as a reaction to what they perceived as the poor design of the (then) popular Jakarta Struts web framework[9], as well as deficiencies in other available frameworks. In particular, they felt there was insufficient separation between the presentation and request handling layers, and between the request handling layer and the model.[Wikipedia - Spring_Framework]

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 106: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 33920130401

Fast Track to Spring 3.x and Spring MVC/REST

General MVC Architecture

Model View Controller– Standard pattern for creating applications with user interfaces

Model: Representation of the business domain– Independent of user interface or application flow– In Java EE typically consisting of data, business objects, JavaBeans for

storing state and data transfer, and other components (e.g. EJB)

View: Way of representing the data to a human user– In Java EE something that generates HTML

• Often a JSP or JSF page• Other resources such as images, charts, etc.

Controller: Intermediary between Model and View– In Java EE Servlets are the core controller components

• May be encapsulated, such as with JSF controllers– Controls user flow through the application, and invokes business logic

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 107: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34020130401

Fast Track to Spring 3.x and Spring MVC/REST

Think twice about going from View to Model

Why?

MVC Pattern flow

M

DB

DAO

FILE

POJO

Servlet

BusinessLogic

CPOJO

HTML

JSP /

JSF

GUIV "Next Best View"

JavaBean

Helper(s)

1. The flow starts with the View, and the user's interaction with any given view.2. The interaction is processed by the controller, which decides whether or not to tweak the model

(Create, Read, Update, Delete)3. The model returns with some data, or a change is made to the model, or there is no need to work

with the model.4. The controller then decides what is the "Next Best View" to show to the user, and the flow starts all

over again.POJO means Plain Old Java Object, which is NOT a Java EE component, as it does NOT require container services. POJOs are making a comeback after heavy weight components failed to deliver based on high expectations. A normal JavaBean (not EJB), and a custom Controller helper (of any non component type) may be considered a POJO.For more on the MVC pattern see, http://en.wikipedia.org/wiki/Model-view-controller

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 108: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34120130401

Fast Track to Spring 3.x and Spring MVC/REST

Spring MVC Architecture

Spring uses a front controller architecture– The front controller is a central servlet that receives all requests,

and dispatches them to other components (controllers) to handle

The main components of a Spring MVC application are:– DispatcherServlet: The front controller servlet– Controllers: Handle specific user requests, generate the data

for response, return a response to determine the view– Handler Mappings: Map URLs to resources (controllers)– Views: Generate HTML Output (JSP, other templates)– View Resolvers: Process response from controllers and direct

the application to the appropriate view (e.g. JSP page)– Model: Spring managed beans

Spring MVC is completely integrated with the Spring container, and allows you to use all of Spring's capabilities

In this front controller architecture, the DispatcherServlet receives all the requests for the Web application

– It is mapped in the web.xml file

The DispatcherServlet dispatches the requests to command controllers, based on the handler mappings

– Handler mappings can be configured when you define the controller beans in the Spring config file

– There are other, more sophisticated, ways to define these mappings also

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 109: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34220130401

Fast Track to Spring 3.x and Spring MVC/REST

Simple Search App Model - Servlets/JSP

Client(browser)

Catalog(Model)

SearchServlet doPost()(Controller + Business)

searchResults.jsp(View)

Request(/search)

Response

Use

forward to searchResults.jsp

In this simple architecture, we've define a servlet to handle the request for doing a search from our JavaTunes online store

– The servlet receives the request, based on its mapping to /search in web.xml, and works with the Catalog (a model class) to get some search results

– It then puts the search results directly on the request, and does a forward to searchResults.jsp– Everything happens in the servlet, including navigation

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 110: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34320130401

Fast Track to Spring 3.x and Spring MVC/REST

Simple Search App Model - Spring MVC

Use

return view name"searchResults"

Client(browser)

Spring MVCDispatcherServlet

SearchController(Business Logic)

View(JSP)

Request(/search.do) Dispatch

Response view name resolved to searchResults.jsp

Catalog(Model)

Response

In the front controller architecture pictured here, the DispatcherServlet receives the request because the URL ends with .do, which is configured in web.xml to map to the Spring MVC DispatcherServlet

– It delegates the request to SearchController, based on the bean definition for the controller– SearchController uses the Catalog model class in the same way as SearchServlet did– SearchController packages up the search results, along with information on what the next

view should be– The DispatcherServlet then puts the search results on the request, and forwards to the

appropriate viewOne advantage to this architecture is that you can use sophisticated ways of determining the next view to forward to - which can be done in a configuration file, rather than hard-coding in your code

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 111: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34420130401

Fast Track to Spring 3.x and Spring MVC/REST

DispatcherServlet

DispatcherServlet: Front controller for Spring MVC– The integration point between Spring MVC and the Web container– It's a standard servlet

DispatcherServlet must be configured in web.xml– To map appropriate requests to the DispatcherServlet– Typically, a pattern such as *.do is used – Requests with a .do suffix (e.g. logon.do) are handled by Spring MVC

<servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet

</servlet-class><load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.do</url-pattern>

</servlet-mapping>

The DispatcherServlet is not created by the developer– It is supplied with the Spring implementation

The configuration elements above are standard Java EE servlet configuration– You can use anything you want for the mapping url pattern– *.do is a common mapping that is used - the logic being that the request needs to do something,

so the URL should indicate this– This mapping is also commonly used by other frameworks, such as Apache Struts

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 112: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34520130401

Fast Track to Spring 3.x and Spring MVC/REST

DispatcherServlet Initialization

The DispatcherServlet has its own WebApplicationContext

– Initialized by the framework when the servlet is initialized– The default config file is: WEB-INF\[servlet-name]-servlet.xml– In our example, it will look for WEB-INF\springmvc-servlet.xml– This file must be present for Spring MVC to initialize

We named our servlet springmvc (in the <servlet-name> element) in the web.xml shown on the previous slide

– This means, that by default the configuration file for the Web application context will be called springmvc-servlet.xml

– You must have the configuration file, even if you don't need to configure anything with it

You can specify the location of the context configuration files by using the contextConfigLocation initialization parameter

– This contains a string containing the configuration file (or files separated by commas)

The DispatcherServlet's context inherits all beans already defined in the root WebApplicationContext

– Which we saw how to initialize in the previous section

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 113: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34620130401

Fast Track to Spring 3.x and Spring MVC/REST

Controllers

Controllers: Spring MVC component to handle requests– Dispatcher servlet forwards requests to controllers– Shields you from low level APIs (e.g. servlet API), interprets user

input, generates a model, and directs response to a view

Controllers are Annotation-based POJOs - the API includes:– @Controller: Indicates the annotated class is a web controller

• Stereotype of @Component - usually auto-detected via scanning• In package org.springframework.stereotype

– @RequestMapping: Maps requests to a controller class/method• In package org.springframework.web.bind.annotation

– RequestMethod: enum of HTTP request methods (e.g. GET)

Component scanning must be enabled to use these– Using context:component-scan as seen earlier

The controller holds the logic that might normally appear in a servlet in a vanilla Servlet/JSP Web app

– For example, you might write a SearchController to take the place of the SearchServletwe saw in the previous section

Using annotations, your controllers can be simple POJOs (Plain Old Java Objects)– They don't have to implement any interfaces or define any particular methods

Instead of working directly with the request attribute to get model data to the next view, it stores the data in a Java class (e.g. a ModelAndView object) that it returns

Similarly, instead of forwarding using a RequestDispatcher, the controller provides the logical information needed to navigate to the next view

– Often, it includes this information in the ModelAndView object that it returns– The DispatcherServlet maps this to an actual view page

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 114: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34720130401

Fast Track to Spring 3.x and Spring MVC/REST

A Very Simple Controller

The simple LogonController below (handling a logon), receives requests of the form /logon.do– @RequestMapping("/logon") specifies the base URL handled– @RequestMapping(method = RequestMethod.GET) specifies

that get() will be used to handle HTTP GET requests– The return value /jsp/logon.jsp specifies the new view for the user

import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;

@Controller@RequestMapping("/logon")public class LogonController {

@RequestMapping(method = RequestMethod.GET)public String get() {return "/jsp/logon.jsp";

}}

In this section, we will work with some simple logon functionality to demonstrate some of the Spring MVC functionality

This simple controller depends on a number of defaults that are pre-configured for Spring MVC– For example, if a handler method returns a simple string, in the absence of any other

configuration, the dispatcher servlet will interpret this as an actual resource to be displayed as the view

– Generally, you use more sophisticated mechanisms for this, which we'll look at shortly

This controller doesn't do anything but display a JSP page at the moment– We will add more functionality soon

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 115: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34820130401

Fast Track to Spring 3.x and Spring MVC/REST

Control Flow

A /logon.do request results in the following flow

– DispatcherServlet receives the request• Based on the *.do mapping in web.xml

– It forwards the request to LogonController.get()• Based on the @Controller and @RequestMapping in the controller• get() returns a value of /jsp/logon.jsp

– DispatcherServlet generates the resulting view• Based on the value /jsp/logon.jsp• Generally, logical view names are used, not file names or paths• We'll see this being done shortly

That's all there is for this simple controller– We'll look at more functionality soon

Note: The controller is detected by component scanning due to its @Controller annotation

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 116: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 34920130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.2 – Spring MVC Basics

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 117: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35020130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.2 – Spring MVC Basics

Overview: In this lab, we'll use some very basic Spring MVC capabilities to implement the same functionality as the last lab– We'll first set up the DispatcherServlet to handle web

requests– Next we'll create a very simple controller to handle a request for

a search form– We'll run our application to see these pieces at work, and in

future labs we'll enhance it to use more Spring MVC capability

Objectives: – Configure DispatcherServlet– Create a controller

Builds on previous labs: none

Approximate Time: 25-35 minutes

Lab

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 118: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35120130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab Preparation

The (new) root lab directory where you will do all your work is:C:\StudentWork\Spring\workspace\Lab06.2

Lab

Tasks to PerformRemove Lab06.1 from the server *, and close all open files/projectsCreate a new Dynamic Web project called Lab06.2– See Lab 6.1 instructions if you need more detail on this– Remember to set the context root to javatunes

Right click on the project in Project Explorer and select Build Path | Configure Build Path and add in the Spring library as before– Next, click Deployment Assembly in the left pane (for configuring Web

app deployment dependencies)– Click Apply if prompted to save modifications– Click Add | Java Build Path Entries click Next, select the Spring

library, click Finish, then OK

To remove the project from the server, do the following– In the Servers view, right click on the server, select Add and Remove Projects– Remove the Lab06.1 project– Restart the server (Right click on the server, select Restart)

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 119: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35220130401

Fast Track to Spring 3.x and Spring MVC/REST

Configure DispatcherServlet Lab

In web.xml, note how Spring's Log4jConfigListener (and associated config param) is included to integrate log4j Spring logging with the web container

– There is nothing you need to do with these – they are already complete

The component-scan element configures scanning and detection for annotated components– Including controller components

We also include an mvc:annotation-driven element– This is not actually necessary for these labs, as the default DispatcherServlet configuration

will include the necessary beans for dispatching requests to annotated controllers– We include it for illustration and completeness

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 120: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35320130401

Fast Track to Spring 3.x and Spring MVC/REST

Configure DispatcherServlet

Tasks to PerformOpen com.javatunes.web.SearchController for editing– It will handle HTTP GET requests to /search.do URLs

Add annotations to SearchController to declare it a controller class, and to map it to the request /search.do– You will need two annotations

Add annotations to get() so that it handles an HTTP GET request– Have it return a value so the /jsp/searchForm.jsp page is displayed as

the view– This JSP page is already given to you, and includes a search form for

performing a search, which we'll use in the next lab

To deploy to the server, right click on the Lab06.2 project, andselect Run As | Run on Server and deploy as in Lab 6.1

Lab

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 121: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35420130401

Fast Track to Spring 3.x and Spring MVC/REST

Test Your Results

Tasks to PerformA browser should open on: http://localhost:<8080>/javatunes– This shows a very simple home page that contains a link to /search.do– Click this link, it should take you to the search form JSP page– This shows that your controller class is being used

When the link for search.do is clicked, the dispatcher servlet receives the request (a GET), and delegates it to your SearchController.get() method– The return value of get() is used to generate the view

You can see how simple it is to build a controller using Spring MVC

Note: Doing a search is NOT yet implemented– It will not work until the next lab

Lab

STOP

To deploy to the server, right click on the Lab06.2 project, and select Run As | Run on Server– Follow the same steps as in Lab 6.1

The search form is defined in the searchHeader.jspf file– This is a JSP fragment, and is included in the other JSP files in the web application that use a

search form

You should get exactly the same view as in the previous lab– We've just replaced our SearchServlet with a command controller invoked by the dispatcher

servlet

Lab 6.2: Spring MVC Basics

Evaluation Copy

Page 122: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35520130401

Fast Track to Spring 3.x and Spring MVC/REST

@RequestParam – Parameter Binding

@RequestParam binds request parameters to controller method arguments

Assume two request parameters for a logon: name and password– They can be bound to method args as shown in the example below

@RequestParam has two other optional elements (see notes)– required: Whether parameter is required– defaultValue: Default value if no value on request

Example: @RequestParam(value="password", required="false")

// Part of LogonController – most detail omitted @RequestMapping(method = RequestMethod.POST)public String processLogon(@RequestParam("name") String name,@RequestParam("password") String password) {// Do logon processing – all detail omittedreturn "/jsp/welcome.jsp";

}

@RequestParam is in package org.springframework.web.bind.annotationThe request parameter name is also optional

– If not given, it will default to the name of the method argument– In our slide example, the default works, so we could write them in the formpublic String processLogon(

@RequestParam String name,

@RequestParam String password)

– We consider it better practice to explicitly include the request parameter name, so the code is not inadvertently broken by someone changing the method

Note that if an annotation has an element named "value" then a value can be given for that element implicitly by using the form we've shown in the slide - @RequestParam("password")

– However, if you want to use other elements in the annotation, then you have to explicitly use the value element's name, as shown in the second example -

@RequestParam(value="password" required="true")

Note that Supplying a default value implicitly sets required to false

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 123: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35620130401

Fast Track to Spring 3.x and Spring MVC/REST

Returning Model Data

Handler methods can return model data for use by the view– A number of model classes are supplied to hold this data

ModelAndView holds both view information and model data– It's in package (org.springframework.web.servlet– Generally used as a return value from a controller method – Has constructors/methods to get/set view, & add attributes to the model

– Some common constructors / methods include:– ModelAndView(String viewName, String modelName,

Object modelObject) • Create an instance with the given view name, model name, and model data

– ModelAndView addObject(String attributeName,

Object attributeValue)• Add an attribute to the model with the given name

– See notes for more methods

Some other methods of ModelAndView include:– ModelAndView addObject(Object attributeValue): Add an attribute to the model

using parameter name generation– Map<String,Object> getModel(): Return the model map.– String getViewName(): Return the view name to be resolved by the DispatcherServlet– void setViewName(String viewName): Set a view name for this ModelAndView– See the javadoc – there are more constructors and methods for added flexibility

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 124: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35720130401

Fast Track to Spring 3.x and Spring MVC/REST

Returning Model Data

The example below uses the constructor shown previously to create a ModelAndView instance and returns it

DispatcherServlet will do the following– Extract the data from the model map– Make model attributes available to the view

• e.g. put them on the request where they can be accessed via JSP EL variables

– Forward to a view page based on the view value

@RequestMapping(method = RequestMethod.POST)public ModelAndView processLogon(@RequestParam("name") String name,@RequestParam("password") String password) {// Assume checkLogon defined elsewhere – detail not shown Principal p = checkLogon(name,password);return new ModelAndView("/jsp/welcome.jsp", "principal", p);

}

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 125: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35820130401

Fast Track to Spring 3.x and Spring MVC/REST

The JSP Pages

Below, we show a logon form and the resulting welcome page– At this point, they're plain JSP pages, with no Spring functionality

The logon submission form:– Submits to logon.do– Includes name and password parameters

The welcome page uses the Principal object that the controller method adds to the model

<!-- Logon submission page --><form method='post'

action='${pageContext.request.contextPath}/logon.do'><input size='20' type='text' name='name'/><input size='20' type='password' name='password'/><input type='submit' name='Submit' value='Logon'/>

</form>

<!-- Welcome page -->Welcome ${principal.name}

Note that we use a number of JSP 2.0 capabilities in the JSP page– ${pageContext.request.contextPath} will evaluate to the Web app context root– ${principal.name} is a JSP EL expression, which in JSP 2.0+ can be mixed with regular template

text• It evaluates to the name property of the principal bean

Spring also includes tag libraries for JSP pages, which we'll look at shortly

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 126: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 35920130401

Fast Track to Spring 3.x and Spring MVC/REST

Other Handler Method Capabilities

Handler methods annotated with @RequestMapping allow other arguments that will be automatically initialized, including:– Request or response objects from Servlet API– Session object: The HttpSession– java.util.Locale: Current request Locale– InputStream/Reader: Raw stream/reader exposed by servlets– OutputStream/Writer: Raw stream/writer exposed by servlets– @RequestHeader annotated parameter: Specific header– @CookieValue annotated parameter: Specific cookie

Return values can include:– ModelAndView, as seen earlier– Model object, with view name implicitly generated from requests– Map object, with view name implicitly generated from request– View object, with model implicitly determined

The controller methods have a lot of different capability– We show some of the more common ones above

Controller methods can also generate the view directly, rather than returning a view to be forwarded to

– For example, by annotating the method with @ResponseBody, and then returning a string that will be used as the response itself

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 127: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36020130401

Fast Track to Spring 3.x and Spring MVC/REST

Example – Other Handler Capabilities

In the example below, we show an example of using some of the additional capabilities of handler methods

// Access HttpServletRequest and HttpServletResonse Objects@RequestMapping("/getServletObjects")public void displayServletInfo(HttpServletRequest request, HttpServletResponse response) { System.out.println(request.getParameter("password"); }

// Access session object and cookie with session id@RequestMapping("/displaySessionInfo")public void displaySessionInfo(HttpSession theSession, @CookieValue("JSESSIONID") String sessID) { /* … */ }

// Access request header values@RequestMapping("/displayHeaderInfo")public void displayHeaderInfo(

@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { /* … */ }

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 128: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36120130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.3 – Parameters and Models

Lab 6.3: Parameters and Model

Evaluation Copy

Page 129: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36220130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.3 – Parameters and Models

Overview: In this lab, we'll extend the functionality of our web app to do the following:– Extract a request parameter– Return a model object that will be used to generate the resulting

view

Objectives: – Extract a request parameter with @RequestParam– Use ModelAndView to return a model

Builds on previous labs: Lab 6.2– Continue working in your Lab06.2 project

Approximate Time: 20-30 minutes

Lab

Lab 6.3: Parameters and Model

Evaluation Copy

Page 130: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36320130401

Fast Track to Spring 3.x and Spring MVC/REST

Finish the Controller

Tasks to PerformOpen com.javatunes.web.SearchController for editingWe configure a Catalog bean, as seen in earlier labs, in the Spring context– Inject this bean into SearchController using @Autowired

• Just declare a field of type Catalog, and apply the Autowiredannotation to it * – we'll use it in our handler method

Add a new method, processSearch() to the controller– It should be called for an HTTP POST– It should have a String argument to hold the keyword, that is

initialized by a "keyword" parameter on the request– Generate the search results by calling Catalog.findByKeyword on

the catalog object using the keyword parameter– If should return a ModelAndView object that

• Specifies a view of jsp/searchResults.jsp• Includes a model attribute with the name results and the search results

Lab

You can see in this lab why auto wiring is so convenient– Just one annotation, and your property is initialized– The trade off, is that you have a less stable application– If there were two catalog beans configured, this simple auto wiring would break

Lab 6.3: Parameters and Model

Evaluation Copy

Page 131: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36420130401

Fast Track to Spring 3.x and Spring MVC/REST

Finish JSP and Run

Tasks to PerformOpen jsp/searchHeader.jspf, and set the action to be search.do(which will cause the form submission to end up at our SearchController to handle)Restart the server so your changes are picked up– Right click on the server, select Restart

Browse back to: http://localhost:<8080>/javatunes– Click on the link for the search form, then type in the letter "a" to search

on and submit the form– The DispatcherServlet will invoke SearchController, which will use a

catalog do the search, and then return a ModelAndView instance initialized with the collection (with name "results") and a view

– The DispatcherSerlvet will then use the ModelAndView instance to put the collection on the request with the name "results", and forward to the view

You should see your search results displayed

Lab

STOP

The search form is defined in the searchHeader.jspf file– This is a JSP fragment, and is included in the other JSP files we use in the web application– Note that we use the same JSP 2.0 capabilities to include the Web app context , which you don't

need to change– You just need to change the part of the action URL that says TODO

You should get exactly the same view as in the first Web integration lab– We've just replaced our SearchServlet with a command controller invoked by the dispatcher

servlet

Lab 6.3: Parameters and Model

Evaluation Copy

Page 132: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36520130401

Fast Track to Spring 3.x and Spring MVC/REST

View Resolvers

It's better practice to use logical view names (e.g. welcome), rather than hard-coded pages (e.g. /jsp/welcome.jsp)

View Resolvers in Spring MVC support this– Used by the dispatcher to map logical names to actual files– InternalResourceViewResolver is a commonly used one

• In package: org.springframework.web.servlet.view– Lets you specify a standard prefix / suffix added to the logical names

to determine the final view page– In the example below, this resolver maps searchResults to the view

page /jsp/searchResults.jsp

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"

value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/jsp/"/><property name="suffix" value=".jsp"/>

</bean>

searchResults.jsp

The InternalResourceViewResolver is a fairly simple view resolver that still requires the controller to know the name of an actual page (though it doesn't necessarily need to know the exact location, or that it is a JSP page

– By simply declaring a bean of this type, it will automatically be detected and used to resolve views

When using the Java Standard Tag Library you must use a special view class, the JstlView, as JSTL needs some preparation before things such as the i18N features will work.

– The viewClass property in the example above configures this

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 133: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36620130401

Fast Track to Spring 3.x and Spring MVC/REST

Controller Using Logical Names

Controllers now use logical view names (not file names)– Below, the two controller methods return logical view names– These will be mapped by the view resolver to actual files– Note that get() is used to initially generate the logon view

@Controller@RequestMapping("/logon")public class LogonController {

@RequestMapping(method = RequestMethod.GET)public String get() { return "logon"; }

@RequestMapping(method = RequestMethod.POST)public ModelAndView processLogon(@RequestParam("name") String name,@RequestParam("password") String password) {// Assume checkLogon defined elsewhere – detail not shown Principal p = checkLogon(name,password);return new ModelAndView("welcome", "principal", p);

}}

You can also use a redirect prefix in the view name to signal a redirect– The special redirect: prefix allows you to easily trigger a redirect from a controller– If a view name is returned that has the prefix redirect:, the UrlBasedViewResolver (and all

subclasses such as InternalResourceViewResolver) will recognize this as a special indication that a redirect is needed

– The rest of the view name will be treated as the redirect UR– redirect:/jsp/aPage.jsp redirects relative to the current context– redirect:http://me.com/aPage.jsp redirects to an absolute URL

You can also indicate a forward using the forward prefix– However, this is rarely needed, as you are basically forwarding to a view by returning a simple

view name

You can also inject the names into a property to make configuration even easier– i.e. Use the value of a property as the logical view name– This property can then be configured in the Spring config file

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 134: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36720130401

Fast Track to Spring 3.x and Spring MVC/REST

Other View Resolvers

BeanNameViewResolver: Maps a view name to a bean– For rendering view with a Java class, rather than JSP - see example at

bottom which maps view name "welcome" to the WelcomeView bean

XmlViewResolver: Uses external XML file to map views to beans– Externalizes bean mappings for views to an XML file– Default XML file is /WEB-INF/views.xml

ResourceBundleViewResolver: Uses external properties files to map views to beans– Allows for localization / internationalization

<!-- Configure the bean name view resolver --><bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

<!-- WelcomeView class used to generate view for view name "welcome" --><bean id="welcome" class="com.javatunes.web.WelcomeView"/>

Spring supplies a number of other view resolvers that follow different strategies– For example, ResourceBundleViewResolver that uses bean definitions in a resource bundle

to resolve views– This allows the mixing of multiple view resolving strategies, as well as localization using the

standard property file naming conventions that Java localization supports– Or XmlViewResolver, that uses bean definitions in an XML file– These allow you to return logical values as the view name, rather than knowing the name of the

page itselfMany of these additional view resolvers specify a Java class that is used to generate the view

– You generate the view in the code for this class, rather than using a template like a JSP– This is useful when you want to do something that JSP is not meant for – like generating an

Excel spreadsheet from model data

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 135: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36820130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.4 – View Resolvers

Lab 6.4: View Resolvers

Evaluation Copy

Page 136: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 36920130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.4 – View Resolvers

Overview: In this lab, we'll add a view resolver to our configuration– The controller will now use logical view names, rather than actual

JSP pages

Objectives: – Work with InternalResourceViewResolver– Use logical names in handler methods

Builds on previous labs: Lab 6.3– Continue working in your Lab06.2 project

Approximate Time: 15-20 minutes

Lab

Lab 6.4: View Resolvers

Evaluation Copy

Page 137: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37020130401

Fast Track to Spring 3.x and Spring MVC/REST

Add a View Resolver

Tasks to PerformOpen WEB-INF\springmvc-servlet.xml for editing– Add a definition for an InternalResourceViewResolver bean– Use a prefix of /jsp/, and a suffix of .jsp– Maps, for example, the logical view name search to /jsp/search.jsp

Open com.javatunes.web.SearchController for editing– Modify both the get() and processSearch() methods to return

logical view names instead of hard coded JPS pages

Restart the server (Right click on server, Restart)

Test your Web app again starting fromhttp://localhost:8080/javatunes– It should all work exactly as before

Lab

STOP

Below, is the bean def for adding in the view resolver

<bean id="jspViewResolver" class=

"org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.JstlView"/>

<property name="prefix" value="/jsp/"/>

<property name="suffix" value=".jsp"/>

</bean>

Lab 6.4: View Resolvers

Evaluation Copy

Page 138: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37120130401

Fast Track to Spring 3.x and Spring MVC/REST

Forms and Command Objects

Integration with Java EESpring MVC Basics

Forms and Command Objects

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 139: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37220130401

Fast Track to Spring 3.x and Spring MVC/REST

Spring MVC Form Tags

Spring MVC uses form tags to give forms access to model attributes– <form:form> renders an HTML 'form' tag and exposes a model object

as a binding path to inner tags for binding• modelAttribute='logon' exposes the logon object within the form *• It puts the object in the PageContext for access by inner tags

– <form:input> renders an HTML 'input' text tag• path='name' binds that input element to the logon.name property

– The initial form view must be generated via a controller, and the form's action comes from the URL associated with that controller• LogonController uses get() to direct a GET of logon.do to this page

<!-- Logon submission page /jsp/logon.jsp --><%@ taglib prefix="form"

uri="http://www.springframework.org/tags/form" %><form:form modelAttribute='logon'><form:input size='20' path='name'/><form:input size='20' path='password'/><input type='submit' name='Submit' value='Logon'/>

</form>

The form tag library allows you to bind a form to a model attribute– By default the form is bound to the model attribute named "command", but that can be

changed with the modelAttribute attribute, as shown above– modelAttribute was called commandName in Spring 2.5 and earlier - it is still supported

The HTML generated from above would be:<form id="logon" method="post" action="/javatunes/logon.do">

<input id="name" name="name" type="text" value="" size="20"/>

<input id="password" name="password" type="password"

value="" size="20"/>

<input type='submit' name='Submit' value='Search'/>

</form>

– The form tags support all the standard HTML attributesWhen using the form tag library, the initial form view MUST go through a controller, in order for the command object to be created and made available when the form renders

– Assuming the form is generated by a request to logon.do, then the action will be as shown in the code above

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 140: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37320130401

Fast Track to Spring 3.x and Spring MVC/REST

A JavaBean Command Class

Spring MVC "command classes" hold form data and possibly model data *– The Logon class below holds a logon name, password, and a Principal object (the result of a successful logon)

– It is a POJO that follows JavaBean conventions for properties• With three properties and their get/set methods

package com.javatunes.web;import java.security.Principal;

public class Logon {private String name;private String password;private Principal principal;

public String getName() {return name;}public void setName(String nameIn) {this.name = nameIn;}// Other get/set methods not shown

}

These are not really command classes in the traditional patterns definition of a command class– They are really just JavaBean data holders– However, Spring MVC uses the terminology "command class", so we will use it also

We've decided to encapsulate our result of the logon processing (the Principal object) into the logon bean

– That is just a design choice - we could have put the principal directly into the model– It doesn't make much difference in terms of functionality, but we use it to illustrate that the

access is slightly different when done this way

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 141: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37420130401

Fast Track to Spring 3.x and Spring MVC/REST

Working with Model Classes

@ModelAttribute binds a method parameter to a model attribute– Used to to expose a command object to a web view by annotating

handler method parameters– This will cause a command object to be created (if not already present

in the model) and bound to the parameterThe example below binds an instance of Logon into the model– It is available to the Web views – note how we initialize it in get()

@RequestMapping(method = RequestMethod.GET)public String get(@ModelAttribute("logon") Logon l) {l.setName("Jane Doe"); // Can initialize the model if you wantreturn "logon"; // Return the view name

}

@RequestMapping(method = RequestMethod.POST)public String processLogon(@ModelAttribute("logon") Logon l) {// Assume checkLogon defined elsewhere – detail not shown l.setPrincipal( checkLogon(l.getName(),l.getPassword()) );return "welcome";

}

In the example above, @ModelAttribute binds the method parameters to a named model attribute– With the model attribute name determined by the element value to ModelAttribute – in this case

logonWhen the get() method is called (presumably as the initial request for the logon form) an instance of Logon is created, and bound into the model with the name "logon"

– It is now available to web views by using this name– Note how data in the model attribute is initialized for the rendering of the form– When the form is displayed, the name input field will be initialized to "Jane Doe"– We show a simple hardcoding of the value, but you could easily use other domain information

for this

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 142: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37520130401

Fast Track to Spring 3.x and Spring MVC/REST

The diagram below shows the flow for initial form renderingThe JSP at bottom shows welcome.jsp (result of a logon)– Note: The principal object is now a property in the logon bean– Before the principal basically was the model

Request Handling Flow

returns "logon"Client

(browser)

Spring MVCDispatcherServlet LogonController

View JSP can usemodel objects

get()

view resolved to/jsp/logon.jsp

Logon (added tomodel)

Response

Request (/logon.do)

Response

<!-- Welcome page – previously used ${principal.name} -->Welcome ${logon.principal.name}

Upon initial request of the form (a GET to logon.do) the DispatcherServlet calls the controllers get() method which results in creation of an instance of the command class (the form backing object)

– It then puts the form backing object on the request– The request is forwarded to the view (the JSP) which can now use the form backing object to

populate the form

Since we've put our Principal object into the logon bean, the access to it is slightly different in the welcome page

– It has to be accessed through the logon bean

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 143: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37620130401

Fast Track to Spring 3.x and Spring MVC/REST

Exposing Reference Data in the Model

@ModelAttribute can be used to expose reference data– By annotating a controller method, as shown below– The example adds a model attribute "previousNames"

• Containing a list of previous logon names - used to populate a select– The Logon class would need a previousName property for this

@ModelAttribute("previousNames")public Collection<String> populateLogonNames() {ArrayList<String> names = new ArrayList<String>();names.add("");names.add("James Gosling");names.add("Jimmy G");return names;

}

<form:form modelAttribute='logon'><form:input size='20' path='name'/><form:input size='20' path='password'/><form:select path="previousName" items="${previousNames}"/><input type='submit' name='Submit' value='Logon'/>

</form>

In the example above, @ModelAttribute applied to a method adds reference data to the model –the method is run when the controller is invoked, and the return value placed in the model

– In the example, we simply hard code the data, but of course you could use more sophisticated means to generate the data (e.g. getting cookie and/or session data)

The reference data is used to populate an HTML select, which is generated by a form:select– The form:select's items attribute refers to the model attribute populating the select– The Logon bean would need a previousNames property, and the path attribute would bind to

this , in the same way that the other input elements of the form bindYour controller could then include logic to check if the previousName property was set, e.g.@RequestMapping(method = RequestMethod.POST)

public String processLogon(@ModelAttribute("logon") Logon l) {

if (l.getPreviousName()!=null && l.getPreviousName().length>0) {

// use the previous name instead of the name property …

}

// remaining detail omitted

}

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 144: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37720130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.5 – Forms and Command Objects

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 145: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37820130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab 6.5 – Forms and Command Objects

Overview: In this lab, we'll expand on the Spring MVC functionality that we use by using the form tag library, and an associated command object to handle the form submission– We'll modify our controller to use the command objects– This will be used in our JavaTunes web app to handle the search

functionality

Objectives: – Use the Spring MVC form tags– Bind model attributes (command objects) to request parameters

Builds on previous labs: none

Approximate Time: 25-35 minutes

Lab

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 146: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 37920130401

Fast Track to Spring 3.x and Spring MVC/REST

Lab Preparation

The (new) root lab directory where you will do all your work is:C:\StudentWork\Spring\workspace\Lab06.5

Lab

Tasks to PerformRemove Lab06.2 from the server *, and close all open files/projectsCreate a new Dynamic Web project called Lab06.5– See Lab 6.1 instructions if you need more detail on this– Remember to set the context root to javatunes

Right click on the project in Project Explorer and select Build Path | Configure Build Path and add in the Spring library as before– Next, click Deployment Assembly in the left pane (for configuring Web

app deployment dependencies)– Click Apply if prompted to save modifications– Click Add | Java Build Path Entries click Next, select the Spring

library, click Finish, then OK

To remove the project from the server, do the following– In the Servers view, right click on the server, select Add and Remove Projects– Remove the Lab06.2 project– Restart the server (Right click on the server, select Restart)

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 147: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38020130401

Fast Track to Spring 3.x and Spring MVC/REST

Finish the Controller

Tasks to PerformOpen com.javatunes.web.Search for review– This is a command class with three properties – a keyword (String),

artist (String) and search results (Collection<MusicItem>)

Open com.javatunes.web.SearchController for editing– Note how get() and processSearch() both have parameters of type

Search – Annotate the parameters in both methods with ModelAttribute so

that they are bound to a model attribute named "search"

Finish get() by initializing the keyword to "Diva"– This value will show up in the initial rendering of the form

Finish processSearch() as follows:– Extract the keyword from the search object, and use it to search– Add the results into the search object

Lab

In processSearch, you're passed a command object– When you initialize the results property of the command object, and your method returns, the

DispatcherServlet makes the command object available to the view– It is then used to render the searchResults.jsp page

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 148: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38120130401

Fast Track to Spring 3.x and Spring MVC/REST

Finish the JSP Pages

Tasks to PerformOpen jsp\searchHeader.jspf for editing (it contains the search form)– Note the taglib for the Spring MVC form tag library at the top– Modify the opening form tag to include the form tag library prefix, and

to bind to the command with a name of "search"– Modify the closing form tag to include the form tag library prefix– Finish the form:input tag's path attribute to bind to the "keyword"

property of the command object

Open jsp\searchResults.jsp for editing (the search results)– The search command bean is available in the results view also– Finish the c:forEach tag's items attribute by initializing it to refer to the

results property of the search bean

Lab

searchHeader.jspf is a JSP fragment that includes the search form– It is structured as a fragment so it can be included in other JSP pages

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 149: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38220130401

Fast Track to Spring 3.x and Spring MVC/REST

Form Initialized and Rendered

We can see the results below– We've browsed to search.do, and the response to that request

has been generated by the form in searchForm.jsp– Note how the keyword field has been initialized to "Diva"

Lab

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 150: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38320130401

Fast Track to Spring 3.x and Spring MVC/REST

Test Your Application

Tasks to PerformDeploy to the server as you did earlier (restart the server)Open a browser on: http://localhost:<8080>/javatunes– Click the link to go to the search form – you should see your default

search term of "Diva"– Do a search – you should see the same results we've seen before– Congratulations - you've made a simple, but complete, Spring MVC app

Optional: Add reference model data to the application– In SearchController, annotate populateArtists() so it adds an

attribute named "artists" into the model– In SearchController, add code to processSearch() to test for and

use the artist property if it has a value of greater than 0 length– In searchHeader.jspf, uncomment/complete the form:select to bind

to the artist property, and initialize the items from the artists attribute– Run the application again and test this functionality

STOP

Lab

For the optional part, we add a collection of strings into the model with the name artists– The form:select uses this model attribute to initialize its set of values– The form:select value binds to the search.artist property, and so becomes available in

the model– The Search class already contains an artist property which can be used for this

Lab 6.5: Forms and Command Objects

Evaluation Copy

Page 151: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38420130401

Fast Track to Spring 3.x and Spring MVC/REST

Review Questions

How do you integrate the Spring container with normal web applications?

What is MVC?

What are the architecture and main components of Spring MVC?

How do you configure Spring's DispatcherServlet? – What does its URL mapping look like?

What does a command controller do? – How is it invoked?

How do controllers help you process forms?– What role to Spring command classes play in this?

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 152: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38520130401

Fast Track to Spring 3.x and Spring MVC/REST

Lesson Summary

The Spring container integrates with normal Web applications via Springs ContextLoaderListener– It automatically loads Spring's root application context and

makes it available to Web apps

MVC: A common pattern for organizing apps with user interfaces into three areas of functionality– Model: Representing the business domain– View: Presenting the data to users– Controller: An intermediary between the model and the view

Spring implements MVC as follows:– Spring beans used as model– Normal view pages (e.g. JSP) as view– Command controllers as its controllers

Session 6: Web Applications with Spring MVC

Evaluation Copy

Page 153: Fast Track to Spring 3.x and Spring MVC/REST · Fast Track to Spring 3.x and Spring MVC/REST on Eclipse/Tomcat Student Guide LearningPatterns, Inc. Courseware Evaluation Copy

Notes:

Copyright © 2007-13 LearningPatterns Inc. All rights reserved. 38620130401

Fast Track to Spring 3.x and Spring MVC/REST

Lesson Summary

Spring's DispatcherServlet is a normal servlet configured in web.xml– Its url-mapping uses patterns, e.g. *.do– This mapping is applicable to a whole category of requests– It acts as a front controller to the web app

Controllers handle incoming requests– They access request data, execute business logic, set up the

model with data, and indicate the next view to render

Controllers can easily process form requests– They can bind method parameters to command classes to gain

access to the form data

Annotations are considered best practice for configuration– They make configuration very simple

Session 6: Web Applications with Spring MVC

Evaluation Copy