Spring MVC Blueprints - Sherwin John Calleja Tragura - E-Book

Spring MVC Blueprints E-Book

Sherwin John Calleja Tragura

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Design and implement real-world web-based applications using the Spring Framework 4.x specification based on technical documentation

About This Book

  • Learn all the details of implementing Spring 4.x MVC applications from basic core platform construction to advanced integration implementations
  • Gain a complete reference guide to implementing the controllers, models, views, view resolvers, and other service-related components to solve various real-world problems
  • Discover the possible optimal solutions for developers and experts to build enterprise and personal web-based applications
  • Create a Spring MVC application that has a validation process and exception handling with the HTTP status codes

Who This Book Is For

This book is for competent Spring developers who wish to understand how to develop complex yet flexible applications with Spring MVC. You must have a good knowledge of JAVA programming and be familiar with the basics of Spring.

What You Will Learn

  • Set up and configure the Spring 4.x MVC platform from ground level up using the basic Spring Framework 4.x APIs
  • Study requirements and manage solutions on file uploading transactions in Spring 4.x applications Configure, , and test Spring integration to the Hibernate, MyBatis, and JPA frameworks for database transactions
  • Properly implement exception handlers and audit trails in Spring MVC applications
  • Generate reports using JFreeChart, Google Charts, JasperReports, DynamicReports, FreeMarker, Velocity, and Spring's API known as ContentNegotiatingViewResolver
  • Configure security and flexibility by adding Captcha, Spring Security, Spring Flow, Spring Portlets, JTA to improve data management performance
  • Implement web services using Spring's RESTful implementation and other service-oriented integration plugins
  • Design and implement a Spring 4.x application using AngularJS, ExtJs, Twitter Bootstrap, and Spring Mobile for responsive web design

In Detail

Spring MVC is the ideal tool to build modern web applications on the server side. With the arrival of Spring Boot, developers can really focus on the code and deliver great value, leveraging the rich Spring ecosystem with minimal configuration.

Spring makes it simple to create RESTful applications, interact with social services, communicate with modern databases, secure your system, and make your code modular and easy to test. It is also easy to deploy the result on different cloud providers.

This book starts all the necessary topics in starting a Spring MVC-based application. Moving ahead it explains how to design model objects to handle file objects. save files into a data store and how Spring MVC behaves when an application deals with uploading and downloading files. Further it highlights form transactions and the user of Validation Framework as the tool in validating data input. It shows how to create a customer feedback system which does not require a username or password to log in. It will show you the soft side of Spring MVC where layout and presentation are given importance. Later it will discuss how to use Spring Web Flow on top of Spring MVC to create better web applications. Moving ahead, it will teach you how create an Invoice Module that receives and transport data using Web Services

By the end of the book you will be able to create efficient and flexible real-time web applications using all the frameworks in Spring MVC.

Style and approach

This book is a compendium of technical specification documents that will guide you through building an application using Spring 4.x MVC. Each chapter starts with a high-level wireframe design of the software followed by how to set up and configure different libraries and tools.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 464

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Spring MVC Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Creating a Personal Web Portal (PWP)
Overview of the project
Technical requirements
Setting-up the development environment
Converting a dynamic web project to a Maven project
Creating a Maven project from scratch
The pom.xml file
Project deployment
Maven deployment process
Project libraries and dependencies
Overview of the Spring MVC specification
The project development
Configuring the DispatcherServlet
Creating the Spring container
Spring container configuration using XML
Spring container configuration using JavaConfig
Configuring the Spring container
Creating the controllers
The PWP controllers
Using @ModelAttribute and @SessionAttributes
Form domain objects
The ViewResolver and view configuration
Actual view pages
Validating Form Data
Validation using JSR 303
Domain data type conversion and filtering
E-mail configuration
The Personal Web Portal (PWP) project
Challenge yourself
Summary
2. Electronic Document Management Systems (EDMS)
Overview of the project
Technical requirement
The pom.xml
The process flow
The project development
Configuring the DispatcherServlet
Creating the Spring container
Creating exception handling for multipart requests
Creating the controllers
Uploading a single document
Uploading multiple documents
Uploading single or multiple documents into the FTP server
Uploading single or multiple files asynchronously
Uploading documents with encryption/decryption
Downloading individual documents from the file system
Downloading individual documents from the FTP server
The form domains
The views
The validators
The EDMS project
Challenge yourself
Summary
3. Student Management Portal (SMP)
An overview of the project
Technical requirements
Implementation A – using the Spring JDBC plugin
Implementation C – using Spring and MyBatis frameworks
Implementation B – using Spring and Hibernate frameworks
Implementation D – using Spring, JPA and Hibernate Frameworks
Software design overview
Configuring the DispatcherServlet
The SMP database
Creating the Spring containers
Implementation A – using a Spring JDBC plugin
jdbc.xml
dao_services.xml
smp_servlet.xml
Implementation B – using Spring and MyBatis frameworks
jdbc.xml
dao_services.xml
Implementation C – using Spring and Hibernate frameworks
jdbc.xml
hibernate.cfg.xml
Implementation D – using Spring, JPA and Hibernate frameworks
jdbc.xml
The persistence.xml
The Data Access Object (DAO) layer
Implementation A – using the Spring JDBC plugin
Implementation B – using Spring and MyBatis Frameworks
Implementation C – using Spring and Hibernate frameworks
Implementation D – using Spring, JPA and Hibernate frameworks
The service layer
Implementation A – using the Spring JDBC plugin
Implementation B – using Spring and MyBatis frameworks
Implementation C – using Spring and Hibernate frameworks
Implementation D – using Spring, JPA and Hibernate frameworks
The data domain layer
Implementation A – using a Spring JDBC plugin
Implementation B – using Spring and MyBatis frameworks
Implementation C – using Spring and Hibernate frameworks
Implementation D – using Spring, JPA and Hibernate frameworks
The controllers
The validators and type conversion
The interceptors
The Aspect, Advice and PointCut
The views
The Student Management Portal (SMP)
Challenge yourself
Summary
4. Human Resource Management System (HRMS)
Overview of the project
Technical requirements
iText 5.x
Apache POI
JExcelAPI
JasperReports
iReport 5.6.0 Visual Designer
DynamicReports
Freemarker Template Language (FTL)
Velocity
JFreeChart
Google Chart
ROME
Software testing libraries
The HRMS database
Data modeling framework
Integrating charts and graphs
Configuring the ViewResolver
The administrator's analytics
The DAO and service layers
The controllers
Line chart
XY line chart
2D bar chart
2D pie chart
Other JFreeChart graphs
The view pages
The HR manager's analytics
The DAO and service layers
The controllers
Line chart
Bar chart
Other Google Chart graphs
The view pages
Integrating reports
PDF document generation using iText 5.x
Excel sheet generation using POI
Excel sheet generation using JExcelAPI
Report generation using JasperReports
Report generation using DynamicReports
Report generation using ContentNegotiatingViewResolver
Generating reports using HTML
FreeMarker Template Language (FTL)
tbl_header.ftl
tbl_body.ftl
tbl_footer.ftl
Velocity
header.vm
footer.vm
Generating news feeds
RSS feeds
Atom Feeds
Handling exceptions
Software testing
Building the test class for unit testing
Building the test class for integration testing
Building the test class for MVC testing
JVM memory management
Client-side visualization
The Human Resource Management System (HRMS)
Challenge yourself
Summary
5. Customer Feedback System (CFS)
Overview of the project
Technical requirements
Captcha libraries
reCaptcha
BotDetect
JCaptcha
SimpleCaptcha
Kaptcha
SendGrid library
The CFS database
Data modeling framework
The Captcha
Posting topics and issues
Adding topics
The reCaptcha controller
The reCaptcha View
Editing topics
The BotDetect controller
The BotDetect view
Giving feedback
The Kaptcha controller
The Kaptcha view
Editing feedback
The SimpleCaptcha controller
The SimpleCaptcha view
E-mail Feedback
The JCaptcha controller
The JCaptcha view
The SendGrid service
The Customer Feedback System (CSF)
Challenge yourself
Summary
6. Hotel Management System (HMS)
Overview of the project
Technical Requirements
Angular JS
JQuery
Twitter Bootstrap
Kickstrap
ExtJS
Thymeleaf
Apache Tiles Framework
SiteMesh
Spring mobile
Spring Roo
The HMS Database
User Experience (UX) design issues
Adaptive web design
Responsive web design
Designing themes
Spring MVC theme support
The Spring Theme configuration
Kickstrap Theme Designs
Kickstrap configuration
Layout design types
Responsive design in Kickstrap
UI components styles
Theme support
Twitter Bootstrap theme design
Fixed grid layout design
Fluid grid layout design
Responsive layout design in Bootstrap
UI components styles
The Thymeleaf design
Configuration
Thymeleaf expressions
Layout and theme
Form handling using Thymeleaf
Rendering results
Internationalization support
Thymeleaf layout design with fragments
Creating intelligent web components
AngularJS
Configuration
The Angular module
ExtJS
The application container
The data model
The data store
The ExtJS view
Controller
The admin room type view
Creating web layouts
Apache tiles 3
Configuration
Creating the template file
Creating the definition file
Adaptive layout design in tiles
SiteMesh 3
Configuration
Creating the decorator
Adaptive layout design in SiteMesh
Spring's internationalization support
Configuration
Creating the resource bundles
The Controller
The View
Velocity, FreeMarker, and Rhythm
Advantage and disadvantage of Velocity
Advantage and disadvantage of FreeMarker
Advantage and disadvantage of Rythm
Spring mobile
Configuration
Device detection
URL Mapping
The Controller
Spring Roo
The Hotel Management System (HMS)
Challenge yourself
Summary
7. Online Cart System (OCS)
Overview of the project
Technical requirements
Spring security
BPMN Activiti
Spring Web Flow
Java Transaction API (JTA)
Bitronix
Spring MVC Portlet
Apache Pluto
JRebel
The OCS database
Data modeling framework
The software prototypes
Spring security implementation
Configuring the DelegatingFilterProxy
Creating the security beans
The <http> tag
The custom login page
Non-Restricted views
Restricted views
Roles and permissions
Types of web authorization
Authentication filter processing
Authentication manager
The UserDetailServiceDao
Password encoding
Authentication failure and success handlers
Session management
Session timeout
URL rewriting
Access denied page
Session fixation protection
Cross-site request forgery
Custom logout page
Post-login transaction
Transaction management using JTA
JTA manager and JEE servers
Tomcat and Bitronix configuration
JNDI configuration
Spring and JTA manager configuration
Bitronix transaction manager (BTM) and JTA
The persistence.xml
JTA DAO transactions
Tomcat 7 and BTM integration
Process and navigation management
Managing workflow using Activiti BPMN 2.0
Database configuration
Database transaction manager
BPMN 2.0 process definition
The process engine
Built-In Activiti services
The controllers
The services
Spring and BPMN layers
Managing workflow using Spring Web Flow
Web flow configuration
Web flow definition
View-states
State transitions
End states
Flow actions
Variable scopes
Spring MVC portlet
OCS as a portal
Controllers
Portlet modes
Portlet views
Application context configuration
Portlet configuration
Defining portlets as portal servlets
Apache Pluto deployment
Spring Cache
Types of cache
Configure caching
Ehcache.xml
Hot deployment using JRebel
Online Cart System (OCS)
Challenge yourself
Summary
8. Enterprise Resource Planning (ERP)
Overview of the project
Technical requirement
Spring Web Services
JAX-WS integration
JAX-RS integration
Jersey RS
RestEasy RS
CXF integration
Axis2 integration
XFire integration
HttpInvoker remoting
Burlap and Hessian remoting
Remote Method Invocation
JMS
Advanced Message Queuing Protocol
ActiveMQ
RabbitMQ
Spring Social
SoapUI
The ERP databases
Data modeling framework
Multiple JNDI data sources
The concept of web services
Consumer-producer relationship
The Spring REST architecture
The Spring-WS Framework
Contract-First versus Contract-Last strategies
Web service generation
Client code generation
JAX-WS
Web service generation (document-based)
Client code generation (document-based)
Web service generation (RPC based)
Client code generation (RPC based)
JAX-RS (RESTful) web services
Web service generation (Jersey)
Media type problem
Web service generation (RestEasy)
Axis2 web service implementation
Web service generation
Web client generation
CXF web service implementation
Web service generation
XFire web service implementation
Web service generation
Web client generation
HttpInvoker, Burlap, and Hessian remoting
Remoting through HttpInvoker
Accessing HttpInvoker services
Remoting through Burlap
Accessing Burlap services
Remoting through Hessian
Accessing Hessian services
Spring containers for remoting
Remote Method Invocation
JMS using ApacheMQ
AMQP using RabbitMQ
Spring Social
The ERP
Challenge yourself
Summary
9. Bus Ticketing System (BTS)
Overview of the project
Technical requirements
AJAX
jQuery
Prototype framework
Dojo
RestEasy AJAX
DWR
WebSocket
jQGrid
The BTS database
Data modeling framework
AJAX and Spring integration
Custom AJAX development
jQuery AJAX
Prototype AJAX
Dojo AJAX
RestEasy JSAPI
Direct web remoting
WebSocket
jQGrid
Google Chart visualization
The Bus Ticketing System (BTS)
Challenge yourself
Summary
10. Social Task Management System (STMS)
Overview of the project
Technical requirements
Spring Data JPA
Spring Data MongoDB
Spring Data REST
Spring Data Solr
Neo4J
Spring integration
Collaborative data analysis concept
Database configuration
Spring Data JPA configuration
Spring Data MongoDB configuration
Database search techniques
Document-based and full-text search
Configuring the Solr server
The Spring-Solr integration
The Spring-Neo4J integration
Configuring the Neo4J graph search server
Spring-Neo4J integration
Integration pitfalls
Codeless REST implementation
Enterprise integration architecture
Social task management system 
Challenge yourself
Summary

Spring MVC Blueprints

Spring MVC Blueprints

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2016

Production reference: 1250716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-827-4

www.packtpub.com

Credits

Author

Sherwin John Calleja Tragura

Copy Editor

Safis Editing

Reviewer

Samer ABDELKAFI

Project Coordinator

Suzanne Coutinho

Commissioning Editor

Priya Singh

Proofreader

Safis Editing

Acquisition Editor

Smeet Thakkar

Indexer

Rekha Nair

Content Development Editor

Zeeyan Pinheiro

Production Coordinator

Aparna Bhagat

Technical Editors

Abhishek Kotian

Vivek Pala

Cover Work

Aparna Bhagat

About the Author

Sherwin John Calleja Tragura started his career as a student assistant and a mathematics tutor during his college years at the University of the Philippines Los Baños, Laguna, Philippines. With meager resources, he graduated as a Department of Science and Technology (DOST) R.A. 7687 scholar under the bachelor of computer science degree. Immediately after graduation, he took up the offer to teach CMSC 150 (numerical and symbolic computation) at the Institute of Computer Science and completed his masters degree in computer science simultaneously. He became part of the International Rice Research Institute (IRRI) software team, which gave him the opportunity to use Struts, Spring, and RCP frameworks in many of its software projects.

Based on his experience at IRRI, he was given the opportunity to work as a Java analyst in various companies in Manila, such as ABSI, PHILAM- AIG, and Ayala Systems and Technology Inc. (ASTI). These companies have strengthened his skillset through training in Java and Java Enterprise platforms and some popular tools such as EMC Documentum and Alfresco Document and Records Management System. He got his first career certification in the EMC Documentum Proven Associate course (E20-120).

After a few years, he decided to become an independent consultant and trainer, providing services mostly on Java-based projects, Alfresco, and Apache OFBiz requirement.  He started his venture as a Java-JEE Bootcamp with 77Global and is currently the trainer at Software Laboratory Inc. (SLI), Alibata Business and Technology Services Inc., and Nityo Infotech, Philippines. He also conducts training and talks around the Philippines such as in Cebu City and Tacloban City.

Sherwin has contributed as a technical reviewer on various books by Packt Publishing, these include: Delphi Cookbook, Alfresco 3 Records Management, Alfresco Share, and Mastering Hibernate. He owes everything to Packt Publishing with the unforgettable experiences on technical editing tasks, which have been an essential part of his career.

As an Oracle Certified Associate and Java SE 7 Programmer (1Z0-803), author will continue his mandate as a technical trainer, developer, architect, and designer to help the industry improve its standards on information technology. He will always be the epitome of honor, excellence, and service when it comes to software development and business intelligence.

This book is dedicated to my father, Cesar Tragura, who passed away on July 8, 2016 while I was adding the finishing touch to this book. I am greatly saddened about your sudden passing, but I know, after all, that you are happy for my first book, and you will always be happy for me and my brother. Thank you for all the memories. Goodbye.

About the Reviewer

Samer ABDELKAFI has over 10 years of experience as a software architect and engineer.

He has contributed to numerous and diverse projects (web applications, data integration, batch, security solutions, web services, and many more) in different sectors, such as banking, insurance, education, public services, and utility billing.

In his free time, he enjoys blogging and sharing his experience on his site (https://samerabdelkafi.wordpress.com).

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

Preface

Many books have been written about Spring Framework that discuss its design patterns and principles, core components, and coding standards and styles, as well as the configuration details of its container, all of which provide a good start to creating a web application. Some literature focuses more on the new features of every release and provides a marketing model for how Spring can help boost the software industry. There are a few that serve as a cookbook of Spring definitions and components for advanced users. Rarely are books written that provide readers with all the core concepts of the Spring specification in collaboration with the most common and popular software libraries, plugins, or frameworks needed to create software with optimal, if not fast, performance, efficient and effective workflows, clever data presentation and business intelligence, standardized graphical user interfaces, and testable, robust, and simple architecture.

This book offers 10 chapters that aim to provide a full guide to maximizing the features of Spring in order to provide technical solutions to some needs from different areas of discipline. It consists of basic concepts about how to start implementing and deploying Spring applications. It provides some new workarounds to Spring users and poses open-ended questions to advanced developers to continue doing research on the Spring 4.x specification.

Writing this book was time consuming since each chapter has its own dedicated software blueprint to be implemented in order to exhibit all the concepts elaborated in the chapters.  Not only the results, but also the technical issues and bugs have been taken into consideration to check whether all functional specifications can fit into one project with the correct API library versions available. Due to time constraints, not all software blueprints are as good as finished products yet, but they are fully executable specimens for the book, covering all the details of the Spring 4.x framework.

What this book covers

Chapter 1, Creating a Personal Web Portal (PWP), highlights the Inverse of Control (IoC) and Dependency Injection (DI) design patterns of the Spring 4.x MVC architecture. All classes and interfaces of Spring 4.x specification, which create the types of controllers, models, and views, including their validators and property editors, are explained by implementing a Personal Web Portal (PWP) prototype that uses only @ModelAttribute and @SessionAttributes to transport and store data through Spring's common page navigations and redirections. Spring MVC applications, Maven deployment and core coding standards are also taken into consideration during prototype development.

Chapter 2, Electronic Document Management Systems (EDMS), focuses on how Spring can handle file upload and download in preparation for some custom document or record management portal development. Through the implementation of a prototype, this chapter discusses how to use Spring’s MultipartFile interface together with HttpServletRequest and MultipartHttpServletRequest for processing documents of any rendition type, with or without encryption/decryption. Also, part of the chapter covers how clients can upload or download file to and from FTP server and how Spring container manage file repository transactions using client-side components such as AJAX.

Chapter 3, Student Management Portal (SMP), showcases the data modeling part of Spring through the use of standard JDBC interfaces and popular object-relational mapping (ORM) frameworks such as Hibernate 4.x  and MyBatis 3.x. Moreover, it also includes JPA configuration to add data persistency to the project. Although this chapter focuses heavily on container configuration, it manages to tackle how to generate data model entities through Spring annotations and map form models to views through Spring's standard tag libraries. On the side, it also demonstrates how to attach auditing functionality through the use of logging framework Log4J and/or Logback.

Chapter 4, Human Resource Management System (HRMS), focuses on writing applications that deal with voluminous data presentation and automated reports with some business intelligence, like that of the HRMS. The prototype provides a mechanism to generate .pdf, .doc, and .xls reports through ContentNegotiatingViewResolver and other related view APIs. For common plugins, HRMS has a functionality that generates those documents through the use of POI and iText libraries. For colorful graphs and charts, this chapter includes GoogleChart and JFreeChart as the main libraries in HRMS for generating data visualizations from hardcoded or database records. Popular enterprise report generation tools such as JasperReports and DynamicReports are also part of the app. On the side, this chapter manages to include exception handling and unit testing in Spring.

Chapter 5, Customer Feedback System (CFS), provides the mechanism to protect application such as CFS from spammers and bots. Applications such as forums or survey portals mainly implement CAPTCHA to prevent unwanted or automated spamming. In this chapter, Spring uses some of the popular CAPTCHA solutions, namely reCaptcha, JCaptcha, SimpleCaptcha, Kaptcha, and BotDetect, to enable protection for CFS. On the side, CFS has a Contact Us functionality that uses SendGrid to manage, secure, and monitor suspicious inbound and outbound e-mail traffic through its email server.

Chapter 6, Hotel Management System (HMS), explains how to build adaptive and responsive web pages in applications that use the Spring framework.  The chapter offers different solutions on how to make applications look friendly on mobile, tablets, and desktops. For intelligent themes, this chapter highlights ThemeResolver to play around with static resources (for example, CSS, JavaScript, and images) of the pages. On creating Single Page Applications (SPA), the chapter discusses using JavaScript objects in ExtJS and AngularJS to process data from the Spring MVC layers. On the other hand, the responsiveness of the HMS pages is discussed further using Twitter Bootstrap and Kickstrap, together with the adaptive tile templates created by Sitemesh and Tiles Framework. Spring integration, Thymeleaf and Spring Mobile is also included in this chapter.

Chapter 7, Online Cart System (OCS), emphasizes workflows and security by creating a prototype of one of the market's popular solution, the e-commerce application.  Aside from custom navigations shown in the previous chapters, this chapter illustrates other smart and advanced solutions to implement formalized business processes through Activiti BPMN 2.0, Spring Web Flow, and Portlet MVC Framework. This chapter also manages to get into the details of Spring Security to provide a comprehensive security solution for any Spring application.

Chapter 8, Enterprise Resource Planning (ERP), helps create software that builds business processes through remote transactions web services just such as an ERP system. This chapter provides a skeleton for how to design interconnected Spring projects through RESTful and SOAP-based services. To start with, the projects have a simple @RestController implementation of the REST web service and we proceed to expand on some advanced integrations with JAX-WS, JAX-RS, Spring WS, CXF, Axis2, and XFire. On the other hand, the ERP successfully integrates Hessian, Burlap, and HttpInvoker to implement remote services between modules. AMQP and JMS have been integrated into this chapter to implement a thin layer of messaging protocol for event handling. This chapter also has side discussions on the 0Auth protocol for adding features on login authentication through Facebook and Twitter Spring Social modules.

Chapter 9, Bus Ticketing Management System (BTS), implements browser-based applications using the Spring MVC specification. Not heavily loaded with Spring components, this chapter is streamlined to use JQuery, Prototype, DWR, and Dojo for data processing and presentation to some applications with a wide range of users, such as BTS. The conversion of data to JSON and XML is also highlighted through the use of the JAXB marshaller for the former and JSON mapping for the latter. Moreover, the chapter promotes JQGrid for intelligent tabular data presentation and GoogleChart JavaScript APIs for data visualization.

Chapter 10, Social Task Management System (STMS), finalizes the extensibility of Spring through the use of Spring Data and Spring Integration modules. This chapter proves that the functional specification of an application can make use of the core and advanced Spring components with fewer libraries. Compacted into one module, this chapter has two applications that have the data repository and service layers with lesser code and fewer processes webbed together using Spring Integration’s channels, service activators, bridges, splitters, and aggregators. Moreover, it illustrates the process to produce web services using inbound gateways and consume RESTful and SOAP-based services using the outbound gateways of Spring Integration.

What you need for this book

Firstly, this book is intended for readers who have a background at least in Java SDK programming. This book does not cover anything about how to start dealing with Java as a language. Secondly, each chapter of this book enumerates the technical requirement to execute the respective Eclipse projects, but the following are the overall general requirements that the user must have:

Any machine with at least 4 GB of RAMJava SDK 1.7.xMaven 3.2.xEclipse STS 3.6 or higherApache Tomcat 7.xApache Solr 5.4Neo4J CE 2.2.10Apache ActiveMQ 5.2.xApache Pluto 2.0.3RabbitMQ 3.5.6Erlang 7.1MongoDB 3.2MySQL 5.6VisualVMSoapUI 5.2.1iReport 5.6.xGoogle Chrome or Mozilla Firefox browser

Lastly, upgrading Java, Maven, and Tomcat versions will require users to recompile the existing Eclipse projects with some changes in Maven library versions to resolve compatibility issues.

Who this book is for

This book has all the chapters for software developers who want to start exploring the Spring framework from its core, for experienced users who want to know more about fine-tuning and integrating the framework to other popular plugins, software frameworks, or tools to solve their work-related requirements, and for experts who want to experiment more with its extensibility in building feasible workarounds and custom-based architecture to solve their respective projects. Each chapter showcases an enterprise application prototype that serves as a guide to illustrate the technical details of how to go about each chapter. It is advisable to accompany each chapter with the Eclipse projects created, which are available for download. Each project may not pass for final production, but is assured to be a finished specimen for the study.

Since this book is a compendium of all the core and advanced concepts of the Spring Framework specification, it is advisable for Spring newbies to read, understand, and crunch Chapters 1 and 3. It is recommended to study the Eclipse projects for each chapter in order to grasp fully the content of the book.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/springmvcblueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1.  Creating a Personal Web Portal (PWP)

This chapter is all about creating a robust and simple personal web portal that can serve as a personal web page, or a professional reference site, for anyone. Usually, these kinds of websites are used as mashups, or dashboards, of centralized sources of information describing an individual or group.

Technically, a personal web portal is a composition of web components like CSS, HTML, and JavaScript, woven together to create a formal, simple or exquisite presentation of any content. It can be used, in its simplest form, as a personal portfolio or an enterprise form like an e-commerce content management system. Commercially, these portals are drafted and designed using the principles of the Rich-client platform or responsive web designs. In the industry, most companies suggest that clients try easy-to-use-tools like PHP frameworks (for example, CodeIgniter, Laravel, Drupal) and seldom advise using JEE-based portals.

Aside from the software processes and techniques that will be discussed in this chapter, the main goal is for the reader to have a quick but detailed review of the main recipe of Spring MVC 4.x implementation, and to know the importance of Java Enterprise Edition (JEE) concepts behind any Java Enterprise frameworks.

In this chapter, you will learn how to:

Implement a complete Spring MVC frameworkConfigure DispatcherServlet in a Spring MVC projectLearn types of controllers and their current featuresUse controller annotationsMap URLs to controllersUse different types of models in dispatching objectsValidate form domain objects using ValidatorConvert and transform request parameter values into other object typesConfigure viewsConfigure and implement e-mail transactionsDeploy Spring MVC projects

Overview of the project

The personal web portal (PWP) created publishes a simple biography, and professional information, one can at least share through the Web. The prototype is a session-driven one that can do dynamic transactions, like updating information on the web pages, and posting notes on the page without using any back-end database.

Through using wireframes, below are the initial drafts and design of the web portal:

The Home Page: This is the first page of the site that shows updatable quotes, and inspiring messages coming from the owner of the portal. It contains a sticky-note feature at the side that allows visitors to post their short greetings to the owner in real-time.The Personal Information Page: This page highlights personal information of the owner including the owner's name, age, hobbies, birth date, and age. This page contains part of the blogger's educational history. The content is dynamic and can be updated at any time by the owner.The Professional Information Page: This page presents details about the owner's career background. It lists down all the previous jobs of the account owner, and enumerates all skills-related information. This content is also updatable.The Reach Out Page: This serves as the contact information page of the owner. Moreover, it allows visitors to send their contact information, and specifically their electronic mail address, to the portal owner.Update pages: The Home, Personal and Professional pages have updateable pages for the owner to update the content of the portal. The prototype has the capability to update the information presented in the content at any time the user desires.

This simple prototype, called PWP, will give clear steps on how to build personal sites, from the ground up, using Spring MVC 4.x specifications. It will give enthusiasts the opportunity to start creating Spring-based web portals in just a day, without using any database backend. To those who are new to the Spring MVC 4.x concept, this chapter will be a good start in building full-blown portal sites.

Technical requirements

In order to start the development, the following tools need to be installed onto the platform:

Java Development Kit (JDK) 1.7.xSpring Tool Suite (Eclipse) 3.6Maven 3.xSpring Framework 4.1Apache Tomcat 7.xAny operating system

First, the JDK 1.7.x installer must be installed. Visit the site http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html to download the installer.

Next, set up the Spring Tool Suite 3.6 (Eclipse-based) which will be the official Integrated Development Environment (IDE) of this book. Download the Spring Tool Suite 3.6 at https://spring.io/tools/sts.

Setting-up the development environment

This book recommends the Spring Tool Suite (Eclipse) 3.6 since it has all the Spring Framework 4.x plug-ins, and other dependencies needed by the projects. To start us off, the following image shows the dashboard of the STS IDE:

Conversely, Apache Maven 3.x will be used to build and deploy the project for this chapter. Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information (https://maven.apache.org/).

There is already a Maven plugin installed in the STS IDE that can be used to generate the needed development directory structure. Among the many ways to create Spring MVC projects, this chapter focuses on two styles, namely:

Converting a dynamic web project to a Maven specimenCreating a Maven project from scratch

Converting a dynamic web project to a Maven project

To start creating the project, press CTRL + N to browse the menu wizard of the IDE. This menu wizard contains all the types of project modules you'll need to start a project. The menu wizard should look similar to the following screenshot:

Once on the menu, browse the Web option and choose Dynamic Web Project. Afterwards, just follow the series of instructions to create the chosen project module until you reached the last menu wizard, which looks like the following figure:

This last instruction (Web Module panel) will auto-generate the deployment descriptor (web.xml) of the project. Always click on the Generate web-xml deployment descriptor checkbox option. The deployment descriptor is an XML file that must reside inside the /WEB-INF/ folder of all JEE projects. This file describes how a component, module or application can be deployed. A JEE project must always be in the web.xml file otherwise the project will be defective.

Note

Since the Spring 4.x container supports the Servlet Specification 3.0 in Tomcat 7 and above, web.xml is no longer mandatory and can be replaced by org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer or  org.springframework.web.servlet.support.AbstractDispatcherServletInitializer class.

The next major step is to convert the newly created dynamic web project to a Maven one. To complete the conversion, right-click on the project and navigate to the Configure | Convert Maven Project command set, as shown in the following image:

It is always best for the developer to study the directory structure of the project folder created before the actual implementation starts. The following is the directory structure of the Maven project after the conversion:

The project directories are just like the usual Eclipse dynamic web project without the pom.xml file.

Creating a Maven project from scratch

Another method of creating a Spring MVC web project is by creating a Maven project from the start. Be sure to install the Maven 3.2 plugin in STS Eclipse. Browse the menu wizard again, and locate the Maven option. Click on the Maven Project to generate a new Maven project.

After clicking this option, a wizard will pop up, asking if an archetype is needed or not to create the Maven project. An archetype is a Maven plugin whose main objective is to create a project structure as per its template. To start quickly, choose an archetype plugin to create a simple Java application here. It is recommended to create the project using the archetype maven-archetype-webapp. However, skipping the archetype selection can still be a valid option.

After you've done this, proceed with the Select an Archetype window shown in the following screenshot. Locate maven-archetype-webapp then proceed with the last process.

The selection of the Archetype maven-archetype-webapp will require the input of Maven parameters before ending the whole process with a new Maven project:

The required parameters for the Maven group or project are as follows:

Group ID (groupId): This is the ID of the project's group and must be unique among all the project's groups.Artifact ID (artifactId): This is the ID of the project. This is generally the name of the project.Version (version): This is the version of the project.Package (package): The initial or core package of the sources.

For more information on Maven plugin and configuration details, visit the documentation and samples on the site http://maven.apache.org/.

After providing the Maven parameters, the project source folder structure will be similar to the following screenshot:

The pom.xml file

The basic fundamental unit of work in Maven is the pom.xml file. This XML file is the main part of the Maven project folder structure, and is always located in the base directory of the project. The file contains all the necessary archetype plugins and dependencies for project building and deployment.

The PWP has this pom.xml file that builds sources, creates project WAR files, and deploys the projects with web.xml to the Tomcat server.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.packt.spring.codes</groupId> <artifactId>ChapterOne</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>ChapterOne</name> <description>Personal Web Portal</description> <!-- properties --> <properties> <spring.version>4.1.2.RELEASE</spring.version> <servlet.api.version>3.1.0</servlet.api.version> </properties> <!-- dependencies --> <dependencies> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!-- Rest of the dependencies in sources --> </dependencies> <build> <finalName>spring-mvc-maven-webapp-from-scratch</finalName> <plugins> <!-- Apache Tomcat 7 Maven Plugin --> <-- <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/manager/text</url> <path>/ch01</path> <username>admin</username> <password>admin</password> </configuration> </plugin> --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <!-- Mojo Maven Plugin --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>TomcatServer</server> <path>/ch01</path> </configuration> </plugin> </plugins> </build> </project>

After setting the development and deployment environment, it is time to start configuring out the Spring MVC component of PWP.

Project deployment

Apache Tomcat 7 will be used as the application server for this chapter. There are two popular Maven plugins that can be used to deploy applications to Tomcat: the Apache Maven plugin and the Mojo Maven plugin. By default, this book uses the Mojo Maven plugin.

To deploy a Maven project to Tomcat using the Mojo Maven plugin, the following configuration must be followed:

Locate the user/conf/tomcat-users.xml file on the Tomcat server and add the desired user with administrator rights. Information like role, username and password of the added user must be added inside the <tomcat-user> tag. A sample configuration is shown in the following code snippet: <role rolename="manager"/> <role rolename="admin"/> <user username="admin" password="admin" roles="admin,manager "/>
Now save the file.
Locate the file ~/.m2/settings.xml in Maven. If the file is non-existent, download Maven from its site and copy the settings.xml to ~/.m2. Open the file and locate the <servers> tag. Insert the following tag inside the <servers> tag. <server> <id>TomcatServer</id> <username>admin</username> <password>admin</password> </server>
The <id> is any desired name for the Tomcat server that will be later called by the pom.xml plugin for Tomcat 7. The <username> and <password> are the server credentials manually added in /conf/tomcat-users.xml above. Save the file.
Open pom.xml and add the following Maven plugin for Tomcat 7 server. <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>TomcatServer</server> <path>/ch01</path> </configuration> </plugin>

The <configuration> settings contain information of where to deploy the project (<url>), what context root to use (<path>/), and the server name (<server>) used in the settings.xml file.

To deploy using the Apache Tomcat7 Maven plugin, the <configuration> tag only needs the <username> and <password> tags of the administration console, including the <url> and the <path>.

Maven deployment process

All projects are deployed in the Tomcat 7 server using the Maven plugin installed in STS. Follow the steps below to properly deploy the Spring MVC projects.

Be sure to have a correctly configured Maven project with the appropriate POM configuration shown in the preceding figure.Right-click on the project and locate Run As in the menu options. Then, locate Maven build... in the sub-menu option, to configure the Maven goals for the first time. Maven goal is a task or command that is executed to build and manage Maven projects.After this, a Maven configuration panel will pop up to write the needed goals for deployment, and to launch the deployment process. If the Mojo Maven plugin is used, write on the Goals textbox the following: clean install tomcat:deploy. If the Apache Tomcat7 Maven plugin is used, the goals must be: clean install tomcat7:deploy. Aside from these goals, there are some that can be essential for management like remove, update and re-deploy.Click the Run button to launch the deployment. All the Maven execution logs will be shown on the console. The outcome of the deployment will be either a BUILD SUCCESS or a BUILD FAILURE.

Project libraries and dependencies

Configure pom.xml to add the major Spring Framework 4.x libraries (JAR files) for the PWP project. These dependency modules are the following:

spring-core (Spring core module): This contains the core components of the framework which includes the Inverse of Control principle and Dependency Injection (DI).spring-beans (Spring bean module): This contains the bean generation using BeanFactory and fetches injected beans using the method getBean().spring-context (Spring context module): Built by the core and bean modules that provide the interfaces of ApplicationContext with some features like resource bundling, internationalization, and scheduling.spring-context-support (Spring context support module): This module contains the classes needed for integrating third-party applications to a Spring Application Context.spring-web: This contains the web features of the Spring Framework which includes the initialization of the IoC container using servlet listeners and a web-oriented application context.spring-webmvc (Spring MVC module): This is the module that has the MVC implementations and features.spring-tx (Spring Transaction module): This contains transaction management on Bean object declarations with some special interfaces for all the POJO objects.

Aside from the other non-framework libraries, the following are auxiliary JAR files that support the Spring Framework 4.x core libraries:

servlet-api: This contains all the classes and interfaces that describe the interaction between a servlet class and the runtime environment provided for the instance of a class within the bound of the servlet container.jsp-api: This contains all the classes that implement the JspPage interface.jstl: This contains all the classes and interfaces for Taglib support for all JSP pages.javax-mail: This provides a platform-independent and protocol-independent framework to build mail and messaging applications.javax.validation: This provides JSR-303 annotations for Java Bean validation.

All of these dependencies must be added to the pom.xml of the Maven project.

Overview of the Spring MVC specification

The Spring MVC framework derives its specification from the Model-View-Controller (MVC) design pattern that separates the application into layers such as business, logic, navigation and presentation. The principle behind this design pattern is to create a de-coupled or loosely-coupled architecture, which is more flexible than the tightly-coupled frameworks.

Technically, Spring MVC works starts with a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution, as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features (http://docs.spring.io/).

The following diagram depicts how DispatcherServlet manages the whole MVC framework while, at the same time, avoiding the Fat Controller syndrome.

The org.springframework.web.servlet.DispatcherServlet is an actual servlet in the web.xml file of your web application, declared using the standard servlet tags. Just like any typical servlets, it recognizes request transactions through URL mappings. This servlet serves as the front controller of the whole MVC project.

Since this PWP project is written using the Spring Framework 4.x specification, the implementations always starts by declaring the DispatcherServlet.

The project development

All the nuts and bolts involved in developing the PWP from scratch will be discussed in this topic. Each of the four web pages, including their internal processes, will be scrutinized using the codes of the project. The Spring MVC concepts will focus on the following areas:

Configuration of DispatcherServletConfiguration of Spring containerCreating controllersTypes of attributesValidationType conversion and transformationE-mail support configurationViews and ViewResolvers

Configuring the DispatcherServlet

We start creating the Spring MVC project by configuring the DispatcherServlet API class. The Spring MVC framework has the DispatcherServlet at the center of all request and response transactions as illustrated in the preceding figure.

From the point of view of the PWP, the DispatcherServlet starts receiving requests when the user starts running pages on the web browser. The processes are enumerated as follows:

When the container receives a request from a path, the DispatcherServlet checks whose controller is mapped to the path name.Then, the controller acknowledges the request with the appropriate service methods (for example, GET, POST, PUT, HEAD), executes the appropriate transaction method with the given model(s), and then returns the view name to the DispatcherServlet.Then, the DispatcherServlet checks which type of view resolver has been configured from its container. Through the view resolver, the DispatcherServlet will know the appropriate view that matches the given request.Finally, the DispatcherServlet will process the transport of model data to the view for presentation or rendition.

The PWP has the following configuration for the DispatcherServlet:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>ChapterOne</display-name> <!-- Declare Spring DispatcherServlet --> <servlet> <servlet-name>pwp</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>pwp</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- Spring accepted extension declared here below --> <mime-mapping> <extension>png</extension> <mime-type>image/png</mime-type> </mime-mapping> </web-app>

Just like any typical JEE servlet, the tags <servlet> and <servlet-mapping> are used to declare the dispatcher servlet DispatcherServlet:

<servlet> <servlet-name>pwp</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>pwp</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>

The <servlet-name> tag does not only stand for the name of the servlet, but is also related to the name of a Spring container which will be tackled later. The  <url-pattern> indicates which type of valid URLs will be recognized by the DispatcherServlet during request-response transactions. In our preceding configuration, it shows that all URL must have an extension .html in order for the requests to be processed by the servlet.

When it comes to file types, the DispatcherServlet only considers content types declared with the <mime-mapping> tag. In this project, we only have PNG files needed by the portal.

<mime-mapping> <extension>png</extension> <mime-type>image/png</mime-type> </mime-mapping>

Creating the Spring container

After we've configured the DispatcherServlet, the Spring MVC container must be created. The interface org.springframework.context.ApplicationContext is Spring's more advanced container. The implementation of this object manages other objects of the portal application that will be known later as beans. All beans are injected into this container so that the portal will just "fetch" them once they are needed in several transactions.

There are two ways to create a Spring MVC container and these are:

XML-based configurationJavaConfig-based configuration

Spring container configuration using XML

Using our STS IDE, the ApplicationContext (applicationContext.xml) can be created using the Spring Eclipse plugin. Following is the menu wizard showing the plugin for the Spring Framework module:

On the wizard, click on the Spring Bean Configuration File option which will guide you to the next instruction panel. This is the selection of the XSD namespaces needed by the applicationContext.xml for the Spring components.

After choosing the necessary XSD namespaces needed for bean injections and configurations, the PWP's XML-based container will look like the following configuration:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> // all beans injected here </beans>

The applicationContext.xml is loaded, accessed, and read by the DispatcherServlet. The convention used so the DispatcherServlet recognizes the container is to name our applicationContext.xml file using the format dispatcherServletName-servlet.xml, wherein the dispatcherServletName is the name indicated by the <servlet-name> tag:

<servlet> <servlet-name>pwp</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet>

Thus, the PWP's applicationContext.xml file is named pwp-servlet.xml. The default filename of an XML-based Spring container must always follow the convention [dispatcher-servlet-name]-servlet.xml.

Spring container configuration using JavaConfig

The other type of implementation of the Spring MVC container is through the JavaConfig classes. In the JavaConfig method, every component tag has its respective annotation equivalent. Following is the equivalent configuration of the preceding XML-based setup.

package org.packt.personal.web.portal.config; import org.springframework.context.annotation.Configuration; @Configuration public class PersonalWebPortalConfig { }

The @Configuration annotation indicates that this class contains one or more bean methods (usually getters) annotated with @Bean that returns manageable beans of the container. Some references call this class a configurator class.

The two implementations are incomparable, but some projects mix them. XML-based Spring MVC containers become cumbersome when the files get larger, while annotation-based ones can be managed since they are just POJO-based. JavaConfig is a better approach when it comes to using a rapid application development (RAD) strategy. The reason for this is that when the number of components in the project increases, JavaConfig can only just manage the dependencies among beans through autowiring, which the XML cannot impose since the codes are decoupled from the dependency injection process. Debugging is also easy, since bug detection will be done during compilation, unlike in the XML-style where errors will be detected right after the deployment or execution of the application.

On the issue of mixing them, the project must choose which configuration is going to be bootstrapped by the container. If it is the JavaConfig, it must use the @ImportResource to load all the injected beans from the XML:

@Configuration @ImportResource("classpath:pws-servlet.xml") public class PersonalWebPortalConfig { }

If the XML-based configuration is used instead, the XML must use <context:component-scan="org.packt.personal.web.portal"/> to locate the @Configuration class and load all @Bean autowired in it.

In general, the XML-based method is preferred, whenever an Enterprise application is being developed, because XML is still widely used in systems integration techniques. Some legacy systems also preferred the XML-based container.

The PWP project has an XML-based and JavaConfig-based container.

Configuring the Spring container

Before we create controllers for our PWP project, the Spring container must be ready for bean injections and component declarations. First, our Spring MVC container must be annotation-driven so that we can utilize the annotation stereotypes used by the current Spring Framework specification in configuring containers.

To enable the use of annotations inside classes, the following tag must be appearing in the pwp-servlet.xml:

<mvc:annotation-driven />

Second, when the <annotation-driven> tag is enabled, the container must automatically scan all component classes that are part of the Spring MVC web project. This will be enabled through inserting the following tag into the pwp-servlet.xml.

<context:component-scan base-package="org.packt.personal.web.portal" />

The base-package attribute indicates the base folder of the development directory structure (src) where all components and beans are located. Declaring this tag enables auto-detection of the bean components in the project, which includes the controllers.

Drop all static resources like the CSS files into the ch01/webapp folder. Declare the default servlet handler in order to allow the access of those static resources from the root of the web application even though the DispatcherServlet is registered at the context root ch01.

<mvc:default-servlet-handler />

Then, use the <mvc:resources> element to point to the location of the static resources with a specific public URL pattern.

<mvc:resources mapping="/css/**" location="/css/" />

The complete XML-based Spring container of PWP is shown as follows:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <mvc:resources mapping="/css/**" location="/css/" /> </beans>

The JavaConfig equivalent of our XML-based container will have this equivalent code:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; // Rest of the imports in sources @Configuration @ComponentScan(basePackages="org.packt.personal.web.portal") @EnableWebMvc public class PWPConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**"). addResourceLocations("/css/"); } }

The @EnableWebMvc annotation is equivalent to <mvc:annotation-driven /> in the XML-based version . Lastly, the @ComponentScan annotation is equivalent to the <context:component-scan base-package=" org.packt.personal.web.portal "/> we have in our pwp-servlet.xml