41,99 €
Design and implement real-world web-based applications using the Spring Framework 4.x specification based on technical documentation
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.
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.
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:
Seitenzahl: 464
Veröffentlichungsjahr: 2016
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
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
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.
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).
For support files and downloads related to your book, please visit www.PacktPub.com.
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.
Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.
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.
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.
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:
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.
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.
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.
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.
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:
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:
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!
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 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.
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.
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:
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:
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.
In order to start the development, the following tools need to be installed onto the platform:
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.
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:
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.
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.
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:
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 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.
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:
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>.
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.
Configure pom.xml to add the major Spring Framework 4.x libraries (JAR files) for the PWP project. These dependency modules are the following:
Aside from the other non-framework libraries, the following are auxiliary JAR files that support the Spring Framework 4.x core libraries:
All of these dependencies must be added to the pom.xml of the Maven project.
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.
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:
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:
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>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:
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.
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.
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
