Book Image

Spring MVC Blueprints

By : Sherwin John C. Tragura
Book Image

Spring MVC Blueprints

By: Sherwin John C. Tragura

Overview of this book

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.
Table of Contents (16 chapters)
Spring MVC Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

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 RAM

  • Java SDK 1.7.x

  • Maven 3.2.x

  • Eclipse STS 3.6 or higher

  • Apache Tomcat 7.x

  • Apache Solr 5.4

  • Neo4J CE 2.2.10

  • Apache ActiveMQ 5.2.x

  • Apache Pluto 2.0.3

  • RabbitMQ 3.5.6

  • Erlang 7.1

  • MongoDB 3.2

  • MySQL 5.6

  • VisualVM

  • SoapUI 5.2.1

  • iReport 5.6.x

  • Google 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.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

All Java codes, and some XML configurations are written in this style:

package org.packt.edms.portal.model.form;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultipleFilesUploadForm {
    private List<MultipartFile> files;
    public List<MultipartFile> getFiles() {
        return files;
    }
    public void setFiles(List<MultipartFile> files) {
        this.files = files;
    }
}

The JavaScript codes of the book are written in this style:

<script type="text/javascript">
define(["dojo/request/xhr","dojo/dom","dojo/on","dojo/domReady!"],
       function(xhr,dom,on){
         var tripId = $('#tripid').val();
         var param = ‘{ id: tripId }’;
         function listDestinations(){ // see the sources    }
           on(dom.byId("custSearchBtn"),
                  "click",callAjaxListing);    } );
</script>

Pure HTML codes use it’s a style like this:

<body>
  <div id="sf-wrapper">
    <div class="container-fluid">
         <div class="row-fluid">
             <div class="span12"> <!--  see the sources -->
       </div></div></div></div>
  </body>

There will be a highlight on certain areas of the code whenever a point is being pointed out:

 Login user = loginDao.getLogin(username.trim());
        try {
         boolean enabled = true;
           boolean accountNonExpired = true;
           boolean credentialsNonExpired = true;
           boolean accountNonLocked = true;
           return new CustomerUserDetails
              (user.getUsername(),user.getEncPassword(), enabled,
               accountNonExpired,credentialsNonExpired,
               accountNonLocked,getAuthorities(user.getId(),
               loginDao.getUserRoleIds(user.getId())));
        } catch (Exception e) {
           throw new RuntimeException(e);
        }

The view names and other general links are written in this style: /ocs/login.html

Filesystem paths, and some API classes and interfaces are in strong style:    

                    /bpmn/cartevents.bpmn20.xml

Server issues, errors, and exceptions are written in screen text style.

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

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:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. 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 Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-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.