Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Spring MVC Cookbook
Spring MVC Cookbook
Spring MVC Cookbook
Ebook1,248 pages14 hours

Spring MVC Cookbook

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Over 40 recipes for creating cloud-ready Java web applications with Spring MVC

About This Book

- Configure Spring MVC to build logic-less controllers that transparently support the most advanced web techniques
- Build an amazing social and financial application that applies microservices patterns on deployment, self-testability, interoperability, cloud architectures, and scalability
- Fast-paced, practical guide to learn how to set up Spring MVC to produce REST resources and templates as required by the latest front-end best practices

Who This Book Is For

If you are an experienced Java developer, with prior experience in web technologies, and want to step up in your career and stay up-to-date or learn more about Spring Web scalability, this book is for you.

What You Will Learn

- Structure your project with Maven and create self-tested, domain-specific deployable web archives
- Generate templates for a responsive and powerful frontend with AngularJS and Bootstrap
- Build a high performance stateless RESTful and hypermedia application to support your multiple customer experiences
- Authenticate over REST with a BASIC authentication scheme and OAuth2; handle roles and permissions
- Document and publish your REST API using Swagger and Swagger UI
- Scale your Spring web application
- Communicate through WebSocket and STOMP messages
- Provide support to your application and efficiently maintain its business features with a relevant test stack

In Detail

Spring MVC is a lightweight application framework that comes with a great configuration by default. Being part of the Spring Framework, it naturally extended and supported it with an amazing set of recognizable annotations. External libraries can be plugged in and plugged out. It also possesses a request flow.
Complete support of REST web services makes the Spring architecture an extremely consistent choice to support your front-end needs and Internet transformations.
From the design of your Maven modules, you will achieve an Enterprise-standard for a stateless REST application based on Spring and Spring MVC with this book.
This guide is unique in its style as it features a massive overview of practical development techniques brought together from the Spring ecosystem, the new JEE standards, the JavaScript revolution and Internet of Things.
You will begin with the very first steps of Spring MVC's product design. Focused on deployment, viability, and maintainability, you will learn the use of Eclipse, Maven, and Git. You will walk through the separation of concerns driven by the microservices principles. Using Bootstrap and AngularJS, you will develop a responsive front-end, capable of interacting autonomously with a REST API.
Later in the book, you will setup the Java Persistence API (JPA) within Spring; learn how to configure your Entities to reflect your domain needs, and discover Spring Data repositories. You will analyze how Spring MVC responds to complex HTTP requests. You will implement Hypermedia and HATEOAS to guide your customer's stateless conversation with the product and see how a messaging-service based on WebSocket can be configured. Finally you will learn how to set up and organize different levels of automated-tests, including logging and monitoring.

Style and approach

A comprehensive, recipe-based guide to creating stunning Java apps with Spring MVC as a result of learning and implementing pro-level practices, techniques, and solutions.
LanguageEnglish
Release dateFeb 25, 2016
ISBN9781784394103
Spring MVC Cookbook

Related to Spring MVC Cookbook

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for Spring MVC Cookbook

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Spring MVC Cookbook - Bretet Alex

    Table of Contents

    Spring MVC Cookbook

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why Subscribe?

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Sections

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Conventions

    Reader feedback

    The showcase application: CloudStreet Market

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Setup Routine for an Enterprise Spring Application

    Introduction

    Why such a routine?

    Why making use of the Eclipse IDE?

    Why making use of Maven?

    What does the Spring Framework bring?

    Installing Eclipse for JEE Developers and Java SE 8

    Getting ready

    How to do it...

    How it works…

    Eclipse for Java EE developers

    Choosing a JVM

    Java SE 8

    Configuring Eclipse for Java 8, Maven 3, and Tomcat 8

    Getting ready

    How to do it...

    How it works...

    The eclipse.ini file

    Setting the –vm option

    Customizing JVM arguments

    Changing the JDK compliance level

    Configuring Maven

    A repository manager

    Tomcat 8 inside Eclipse

    There's more...

    Defining the project structure with Maven

    Getting ready

    How to do it...

    How it works...

    New Maven project, new Maven module

    The standard project hierarchy

    The project's structure in the IDE

    Maven's build life cycles

    The clean life cycle

    The default life cycle

    Plugin goals

    Built-in life cycle bindings

    About Maven commands

    There's more...

    How did we choose the jar module's name?

    How did we choose the names for deployable modules?

    Why did we create core modules?

    See also...

    Installing Spring, Spring MVC, and a web structure

    Getting ready

    How to do it...

    How it works...

    Inheritance of Maven dependencies

    Basic inheritance

    Managed inheritance

    Including third-party dependencies

    The Spring Framework dependency model

    The Spring MVC dependency

    Using Maven properties

    The web resources

    The target runtime environment

    The Spring web application context

    Plugins

    The Maven compiler plugin

    The Maven surefire plugin

    The Maven enforcer plugin

    The Maven war plugin

    There's more...

    See also

    The Maven checkstyle plugin

    2. Designing a Microservice Architecture with Spring MVC

    Introduction

    The User eXperience paradigm

    Microservice architectures

    Configuring a controller with simple URL mapping

    Getting ready

    How to do it...

    Downloading and installing GIT

    Configuring GIT in Eclipse

    How it works...

    Spring MVC overview

    Front controller

    MVC design pattern

    Spring MVC flow

    DispatcherServlet – the Spring MVC entrypoint

    Annotation-defined controllers

    @Controller

    @RequestMapping

    Controller method-handler signatures

    Supported method arguments types

    Supported annotations for method arguments

    Supported return Types

    There's more...

    Configuring a fallback controller using ViewResolver

    Getting ready

    How to do it...

    How it works...

    URI template patterns

    Ant-style path patterns

    Path pattern comparison

    ViewResolvers

    There's more...

    @PathVariable to read variables in URI template patterns

    Setting up and customizing a responsive single page webdesign with Bootstrap

    Getting ready

    How to do it...

    Installing a Bootstrap theme

    Customising a Bootstrap theme

    Creating responsive content

    How it works...

    The theme installation

    Bootstrap highlights

    Bootstrap scaffolding

    Grid system and responsive design

    Defining columns

    Offsetting and nesting

    Fluid gridding

    Bootstrap CSS utilities

    Uniform Buttons

    Icons

    Tables

    Bootstrap components

    Navbars

    Hero units

    Alerts

    Badges and labels

    There's more...

    See also

    Displaying a model in the View, using the JSTL

    Getting ready

    How to do it...

    How it works...

    The approach to handle our data

    Injection of services via interfaces

    How does Spring choose the dummy implementations?

    DTOs to be used in View layer

    Dummy service implementations

    Populating the Model in the controller

    Rendering variables with the JSP EL

    Implicit objects

    Rendering variables with the JSTL

    Taglib directives in JSPs

    There's more...

    More about JSP EL

    More about the JavaBeans standard

    More about the JSTL

    Defining a common WebContentInterceptor

    Getting ready

    How to do it...

    How it works...

    Common behaviors for Controllers

    Global session control

    Requiring sessions

    Synchronizing sessions

    Cache-header management

    HTTP method support

    A high-level interceptor

    Request lifecycle

    There is more...

    More features offered by WebContentGenerator

    See also...

    Web caching

    New support classes for @RequestMapping since Spring MVC 3.1

    Designing a client-side MVC pattern with AngularJS

    Getting ready

    How to do it...

    Setting up the DOM and creating modules

    Defining the module's components

    How it works...

    One app per HTML document

    Module autobootstrap

    Manual module bootstrap

    AngularJS Controllers

    Bidirectional DOM-scope binding

    AngularJS directives

    ng-repeat

    ng-if

    AngularJS factories

    Dependency injection

    There's more...

    3. Working with Java Persistence and Entities

    Introduction

    The Entities' benefits

    The Entity manager and its persistence context

    Configuring the Java Persistence API in Spring

    Getting ready

    How to do it...

    How it works...

    The Spring-managed DataSource bean

    The EntityManagerFactory bean and its persistence unit

    The Spring Data JPA configuration

    See also

    Defining useful EJB3 entities and relationships

    Getting ready

    How to do it...

    How it works...

    Entity requirements

    Mapping the schema

    Mapping tables

    Mapping columns

    Annotating fields or getters

    Mapping primary keys

    Identifier generation

    Defining inheritance

    The single-table strategy

    The table-per-class strategy

    Defining relationships

    How relationships between entities have been chosen

    There's more...

    The FetchType attribute

    The Cascade attribute

    See also

    Making use of the JPA and Spring Data JPA

    How to do it...

    How it works...

    Injecting an EntityManager instance

    Using JPQL

    Reducing boilerplate code with Spring Data JPA

    Query creation

    Persisting Entities

    There's more...

    Using native SQL queries

    Transactions

    See also

    4. Building a REST API for a Stateless Architecture

    Introduction

    A definition of REST

    RESTful CloudStreetMarket

    Binding requests and marshalling responses

    Getting ready

    How to do it...

    How it works...

    A super RequestMappingHandlerAdapter bean

    Broad support for @RequestMapping annotations

    setMessageConverters

    setCustomArgumentResolvers

    setWebBindingInitializer

    The ConversionService API

    Choosing between PropertyEditors or converters

    There's more...

    Built-in PropertyEditor implementations

    The Spring IO reference document

    Configuring content-negotiation (JSON, XML, and so on)

    Getting ready

    How to do it...

    How it works...

    Support for XML marshalling

    The XStream marshaller

    Negotiation strategies with ContentNegotiationManager

    The Accept header

    The file extension suffix in the URL path

    The request parameter

    Java Activation Framework

    @RequestMapping annotations as ultimate filters

    There's more...

    Using a JAXB2 implementation as an XML parser

    The ContentNegotiationManagerFactoryBean JavaDoc

    Adding pagination, filters, and sorting capabilities

    Getting ready

    How to do it...

    How it works...

    Spring Data pagination support (you will love it!)

    Pagination and sorting in repositories

    PagingAndSortingRepository

    The web part – PageableHandlerMethodArgumentResolver

    A useful specification argument resolver

    The JPA2 criteria API and Spring Data JPA specifications

    SpecificationArgumentResolver

    There's more...

    Spring Data

    Angular routes

    See also

    Bootstrap pagination with the Angular UI

    Handling exceptions globally

    Getting ready

    How to do it...

    How it works...

    Global exception handling with @ControllerAdvice

    The support ResponseEntityExceptionHandler class

    A uniform error response object

    There's more...

    HTTP Status Codes

    The official article about exception handling in Spring MVC

    JavaDocs

    See also

    Documenting and exposing an API with Swagger

    Getting ready

    How to do it...

    How it works...

    An exposed metadata

    The Swagger UI

    There's more...

    The Swagger.io

    The swagger-springmvc documentation

    See also

    Different tools, different standards

    5. Authenticating with Spring MVC

    Introduction

    Configuring Apache HTTP to proxy your Tomcat(s)

    Getting ready

    How to do it...

    How it works...

    DNS configuration or host aliasing

    In production – editing DNS records

    An alias for the host

    Alias definition for OAuth developments

    Apache HTTP configuration

    Virtual-hosting

    The mod_proxy module

    ProxyPassReverse

    Workers

    The mod_alias module

    Tomcat connectors

    HTTP connectors

    AJP connectors

    There is more…

    See also

    Alternatives to Apache HTTP

    Adapting users and roles to Spring Security

    Getting ready

    How to do it...

    How it works...

    Introduction to Spring Security

    ThreadLocal context holders

    Noticeable Spring Security interfaces

    The Authentication interface

    The UserDetails interface

    Authentication providers

    The UserDetailsManager interface

    The GrantedAuthority interface

    There is more…

    Spring Security reference

    Technical overview

    Sample applications

    Core services

    Authenticating over a BASIC scheme

    Getting ready

    How to do it...

    How it works...

    The Spring Security namespace

    The component

    The Spring Security filter-chain

    Our configuration

    The AuthenticationManager interface

    Basic authentication

    BasicAuthenticationFilter

    With an authenticationEntryPoint

    Without an authenticationEntryPoint

    There is more…

    In the Spring Security reference

    The remember-me cookie/feature

    Authenticating with a third-party OAuth2 scheme

    Getting ready

    How to do it...

    How it works...

    From the application point of view

    From the Yahoo! point of view

    OAuth2 explicit grant flow

    Refresh-token and access-token

    Spring social – role and key features

    Social connection persistence

    Provider-specific configuration

    One entry-point – connectionFactoryLocator

    Provider-specific ConnectionFactories

    Signing in with provider accounts

    There is more…

    Performing authenticated API calls

    The Spring social ConnectController

    See also

    SocialAuthenticationFilter

    The list of Spring social connectors

    Implementing an OAuth2 authentication server

    The harmonic development blog

    Storing credentials in a REST environment

    Getting ready

    How to do it...

    Client side (AngularJS)

    Server side

    How it works...

    Authenticating for Microservices

    Using the BASIC authentication

    Using OAuth2

    HTML5 SessionStorage

    SSL/TLS

    BCryptPasswordEncoder

    There is more…

    Setting HTTP headers with AngularJS

    Browser support for localStorage

    About SSL and TLS

    Authorizing on services and controllers

    Getting ready

    How to do it...

    How it works...

    Spring Security authorities

    Configuration attributes

    Pre-invocation handling

    AccessDecisionManager

    After invocation handling

    Expression-based access control

    Web Security expressions

    Method security expressions

    Access control using @PreAuthorize and @PostAuthorize

    Filtering collections using @PreFilter and @PostFilter

    JSR-250 and legacy method security

    There is more…

    Domain Object Security (ACLs)

    Spring EL

    The Spring Security reference

    See also

    6. Implementing HATEOAS

    Introduction

    The Richardson Maturity Model

    Turning DTOs into Spring HATEOAS resources

    How to do it…

    How it works...

    Spring HATEOAS resources

    The ResourceSupport class

    The Resource class

    The Identifiable interface

    Abstracting the Entities' @Id

    There's more…

    See also

    Building links for a hypermedia-driven API

    How to do it…

    How it works...

    Resource assemblers

    PagedResourcesAssembler

    Building links

    EntityLinks

    ControllerLinkBuilder

    There's more…

    The use of regular expressions in @RequestMapping

    See also

    Choosing a strategy to expose JPA Entities

    How to do it…

    How it works...

    The REST CRUD principle

    Exposing the minimum

    If the Entity doesn't own the relationship

    If the Entity owns the relationship

    Separation of resources

    There's more…

    Jackson custom serializers

    XStream converters

    Retrieving data from a third-party API with OAuth

    How to do it…

    How it works...

    Introduction to the financial data of Yahoo!

    Graph generation/display

    How is the financial data pulled/refreshed?

    Calling third-party services

    There's more…

    Spring Social — existing API providers

    See also

    7. Developing CRUD Operations and Validations

    Introduction

    Extending REST handlers to all HTTP methods

    Getting ready

    How to do it…

    How it works...

    HTTP/1.1 specifications – RFC 7231 semantics and content

    Basic requirements

    Safe and Idempotent methods

    Other method-specific constraints

    Mapping request payloads with @RequestBody

    HttpMessageConverters

    Provided HttpMessageConverters

    Using MappingJackson2HttpMessageConverter

    Using @RequestPart to upload an image

    Transaction management

    The simplistic approach

    There's more…

    Transaction management

    ACID properties

    Global versus local transactions

    See also

    Validating resources using bean validation support

    Getting ready

    How to do it…

    How it works...

    Using Spring validator

    ValidationUtils

    I18n validation errors

    Using JSR-303/JSR-349 Bean Validation

    On-field constraint annotations

    Implementation-specific constraints

    LocalValidator (reusable)

    There's more…

    ValidationUtils

    Grouping constraints

    Creating a custom validator

    The Spring reference on validation

    See also

    Internationalizing messages and contents for REST

    How to do it…

    Backend

    Frontend

    How it works...

    MessageSource beans

    ResourceBundleMessageSource

    ReloadableResourceBundleMessageSource

    StaticMessageSource

    Our MessageSource bean definition

    Using a LocaleResolver

    AcceptHeaderLocaleResolver

    FixedLocaleResolver

    SessionLocaleResolver

    CookieLocaleResolver

    There's more…

    Translating client-side with angular-translate.js

    Validating client-side forms with HTML5 AngularJS

    How to do it…

    How it works...

    Validation-constraints

    Required

    Minimum/maximum length

    Regex pattern

    Number/e-mail/URL

    Control variables in forms

    Modified/Unmodified state

    Valid/Invalid state

    Errors

    Form state transclusions and style

    See also

    8. Communicating Through WebSockets and STOMP

    Introduction

    Streaming social events with STOMP over SockJS

    Getting ready

    How to do it…

    Apache HTTP Proxy configuration

    Frontend

    Backend

    How it works...

    An introduction to WebSockets

    WebSocket Lifecycle

    Two dedicated URI schemes

    The STOMP protocol

    SockJS

    Spring WebSocket support

    All-in-one configuration

    Defining message handlers via @MessageMapping

    Sending a message to dispatch

    SimpMessagingTemplate

    The @SendTo annotation

    There's more…

    See also

    Using RabbitMQ as a multiprotocol message broker

    Getting ready

    How to do it…

    How it works...

    Using a full-featured message broker

    Clusterability – RabbitMQ

    More STOMP message types

    StompMessageBrokerRelay

    See also

    Stacking and consuming tasks with RabbitMQ and AMQP

    Getting ready

    How to do it…

    Sender side

    Consumer side

    Client-side

    How it works...

    Messaging architecture overview

    A scalable model

    AMQP or JMS?

    There's more…

    A great introduction to AMQP by pivotal

    A better way to publish application events

    See also

    Securing messages with Spring Session and Redis

    Getting ready

    How to do it…

    Apache HTTP proxy configuration

    Redis server installation

    MySQL server installation

    Application-level changes

    RabbitMQ configuration

    The results

    How it works...

    The Redis server

    Spring session

    SessionRepositoryFilter

    RedisConnectionFactory

    CookieHttpSessionStrategy

    Spring Data Redis and Spring Session Data Redis

    The Redis Session manager for Tomcat

    Viewing/flushing sessions in Redis

    securityContextPersistenceFilter

    AbstractSessionWebSocketMessageBrokerConfigurer

    AbstractSecurityWebSocketMessageBrokerConfigurer

    There's more…

    Spring Session

    Apache HTTP proxy extra configuration

    Spring Data Redis

    See also

    9. Testing and Troubleshooting

    Introduction

    Automating Database Migrations with FlyWay

    Getting ready

    How to do it…

    How it works...

    A limited number of commands

    Migrate

    Clean

    Info

    Validate

    Baseline

    Repair

    About Flyway Maven plugin

    There is more…

    The official documentation

    See also

    Unit testing with Mockito and Maven Surefire

    How to do it…

    How it works...

    @Test annotation

    The expected and timeout arguments

    The @RunWith annotation

    @Before and @After annotations

    @BeforeClass and @AfterClass annotations

    Using Mockito

    MockitoJUnitRunner

    The transferCriticalData example

    The registerUser example

    There is more…

    About Mockito

    JUnit Rules

    See also

    Integration testing with Cargo, Rest-assured, and Maven failsafe

    Getting ready

    How to do it…

    How it works...

    Maven Failsafe versus Maven Surefire

    Code Cargo

    Cargo Maven Plugin

    Binding to Maven phases

    Using an existing Tomcat instance

    Rest assured

    Static imports

    A Given, When, Then approach

    There is more…

    About Cargo

    More REST-assured examples

    Injecting Spring Beans into integration tests

    Getting ready

    How to do it…

    How it works...

    SpringJUnit4ClassRunner

    The @ContextConfiguration annotation

    There is more…

    JdbcTemplate

    Abstraction of boilerplate logic

    Extraction of auto-generated IDs

    Modern application Logging with Log4j2

    Getting ready

    How to do it…

    How it works...

    Apache Log4j2 among other logging frameworks

    The case of SLF4j

    Migrating to log4j 2

    Log4j 2 API and Core

    Log4j 2 Adapters

    Log4j 1.x API Bridge

    Apache Commons Logging Bridge

    SLF4J Bridge

    Java Util Logging Adapters

    Web Servlet Support

    Configuration files

    There is more…

    Automatic configuration

    Official documentation

    Interesting Redis Appender implementation

    Index

    Spring MVC Cookbook


    Spring MVC Cookbook

    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: February 2016

    Production reference: 1220216

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78439-641-1

    www.packtpub.com

    Credits

    Author

    Alex Bretet

    Reviewers

    Bartosz Kielczewski

    David Mendoza

    Commissioning Editor

    Amarabha Banerjee

    Acquisition Editor

    Manish Nainani

    Content Development Editor

    Mayur Pawanikar

    Technical Editor

    Pranjali Mistry

    Copy Editor

    Neha Vyas

    Project Coordinator

    Nikhil Nair

    Proofreader

    Safis Editing

    Indexer

    Monica Ajmera Mehta

    Production Coordinator

    Nilesh Mohite

    Cover Work

    Nilesh Mohite

    About the Author

    Alex Bretet is a certified Java and Spring Integration engineer. Currently working at Thunderhead, a pioneer company and global actor among SaaS providers, he has a rich developer background from different industries including energy, insurance, finance, and the Internet.

    Captivated by the Internet's communication capabilities and by start-ups, he believes in skunk development outcomes (when groups of like-minded people together achieve unbelievable targets on tight deadlines).

    He also defends a number of open source initiatives and indeed Spring technologies, whose pragmatism constantly disrupts the most established practices and offers valuable alternatives for the benefit of all.

    You can contact him at <alex.bretet@gmail.com> or follow him on Twitter at @abretet

    I would like first to thank all the people who have been directly related to this book, starting with all the reviewers, content development editors, technical and acquisition editors.

    My thoughts go to my French engineering school and all the people I've met since then who have expressed and communicated their enthusiasm for the technology.

    I am very grateful for being able to work in the IT industry nowadays. Thank you to all the elements around me that supported me going in this direction. When my interest for this topic grew, I couldn't imagine making a career out of it.

    Writing this book has been a long project. I must mention my partner, Helena, for her patience and support throughout these months; my family and friends, who have been a source of encouragement; my dad, a source of inspiration.

    My best regards go to Packt Publishing for producing this book and endorsing the project.

    I acknowledge the expertise from the engineers at Pivotal Software, Inc. and the Spring community, their approachable set of documentation and their official references.

    Finally, I want to thank you, who are reading these lines and have probably purchased this book. I hope it will provide you help, spark, and Big Picture.

    About the Reviewer

    David Mendoza is a software engineer working on web development since 1999 with Java. He started his journey with JSPs and Servlets, creating a custom web framework to later find AppFuse, which introduced him to Spring and Struts. Then, he moved to Spring MVC and never looked back. David has worked as a Java consultant in Mexico, the United States, Canada, Venezuela, and Spain with companies such as ING Bank, Citi, and Telefonica. He is currently working for Southwestern Adventist University, a private university south of Dallas, Texas, where he's responsible for their entire web platform.

    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 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 Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    Welcome to the singular universe of Spring MVC Cookbook. We hope you are ready for this journey that will take you through modern Spring web development practices. We have been building the cloudstreetmarket.com , a stock exchange platform with social capabilities. We are about to take you through each step of its development process.

    What this book covers

    Chapter 1, Setup Routine for an Enterprise Spring Application, introduces a set of practices that are standard in the industry. From the configuration of an Eclipse IDE for optimized support of Java 8, Tomcat 8, GIT and Maven, to a proper understanding of Maven as a build automation tool and as a dependency management tool, you will learn how to deploy the Spring Framework on a sustainable base in this chapter.

    Whether a project is meant to become a massively profitable product or to remain a rewarding experience, it should always begin with the same Enterprise-level patterns.

    This chapter is more than a guide through the first development stage of the book's application, Cloud Street Market. A bunch of standard practices are presented here as a routine for developers toward enterprise Spring applications.

    Chapter 2, Designing a Microservice Architecture with Spring MVC, is a slightly longer chapter. It covers the core principles of Spring MVC, such as its request flow or the central role of DispatcherServlet. It is also about learning how to configure Spring MVC controllers and controller method-handlers with an extended source of information related to a controller's annotations.

    In the path of a Microservice architecture, we install Spring and Spring MVC across modules and web projects to build functional units that are easy to deploy and easy to scale. In this perspective, we are going to shape our application with a web module that is responsible for serving a Twitter Bootstrap template along with another web module specialized in REST Web Services.

    In this chapter, you also will learn how to transfer the model from controllers to JSP views using the JSTL and how to design a JavaScript MVC pattern with AngularJS.

    Chapter 3, Working with Java Persistence and Entities, gives you a glimpse of . It is necessary at this stage to learn how persistent data can be handled in a Spring ecosystem and thus in a Spring MVC application. We will see how to configure, a JPA persistence provider (Hibernate) from dataSource and entityManagerFactory in Spring. You will learn how to build a beneficial JPA object-relational mapping from EJB3 Entities and then how to query repositories using Spring Data JPA.

    Chapter 4, Building a REST API for a Stateless Architecture, provides insights into Spring MVC as a REST Web Services engine. We will see the amazing support the Framework provides, with several annotations acting as doorknobs on method-handlers to abstract web-related logic and thus only focus on the business. This principle appears with annotations for request binding (binding of parameters, URL paths, headers, and so on) and Response Marshalling and also for integrated support of Spring Data pagination.

    This chapter also presents how to set up exception handling as part of Spring MVC to translate predefined exception-Types into generic error responses. You will understand how to configure the content negotiation, an important bit for REST APIs, and finally, how to expose and document REST Endpoints using Swagger and the Swagger UI.

    Chapter 5, Authenticating with Spring MVC, presents how to configure an authentication on controllers and services from standard protocols such as HTTP BASIC and OAuth2. You will learn several concepts and practices related to Spring Security, such as the Filters chain, the namespace, the Authentication Manager, or the management of roles and users. Our OAuth2 flow is a client implementation. We authenticate users in our application when they are first authenticated with a third-party provider: Yahoo! These Yahoo! authentications and connections are later used to pull fresh financial data from Yahoo! Finance. It will be very interesting to see how the OAuth2 flow can be entirely abstracted, in the backend, with the Spring Social library.

    Chapter 6, Implementing HATEOAS, demonstrates how to take a RESTful Spring MVC API a step further. A Hypermedia-driven application provides links along with every single requested resource. These links reflect URLs of related resources. They provide to the user client (whatever type of client it may be) real-time navigation options—precious documentation that is also the actual implementation.

    We will see how to build such links from JPA Entities associations or from the controller layer.

    Chapter 7, Developing CRUD Operations and Validations, goes into the more advanced concepts of Spring MVC. Presenting the tools and techniques that support interactive HTTP methods (PUT, POST, and DELETE), we will lean on the HTTP1/1 specification (RFC 7231 Semantics and Content) to learn how to return the appropriate response status code or headers.

    Our use of the Spring Validator together with the ValidationUtils utility class provides a compliant implementation of the validation-related JSR-303 and JSR-349 specifications.

    The last recipe is the place where an internationalization (I18N) of messages and content happens. We also present a client-side implementation, with AngularJS, that relies on published internationalization web services.

    Chapter 8, Communicating Through WebSockets and STOMP, focuses on the uprising WebSocket technology and on building Message-Oriented-Middleware for our application. This chapter provides a rare showcase that implements so much about WebSockets in Spring. From the use of the default embedded WebSocket message broker to a full-featured external broker (with STOMP and AMQP protocols), we will see how to broadcast messages to multiple clients and also how to defer the execution of time-consuming tasks with great scalability benefits.

    You will learn how to dynamically create private queues and how to get authenticated clients to post and receive messages from these private queues.

    To achieve a WebSocket authentication and an authentication of messages, we will make the API stateful. By stateful, understand that the API will use HTTP sessions to keep users authenticated between their requests. With the support of Spring Session and the highly clusterable Redis server, sessions will be shared across multiple web apps.

    Chapter 9, Testing and Troubleshooting, introduces a set of tools and common practices to maintain, debug, and improve an application's state. As a way of finishing this journey, we will visit how to upgrade the database schema from one version of the application to another as part of the Maven builds with the Flyway Maven Plugin. We will also go through how to write and automate unit tests (with Maven Surefire and Mockito) and integration tests (using a set of libraries such as Cargo, Rest-assured, and Maven Failsafe).

    The last recipe provides insightful guidelines in order to apply Log4j2 globally as a logging framework, as it is more than important to rely on a relevant logging solution to troubleshoot efficiently, whichever environment we may be on.

    What you need for this book

    The hardware and software list details the requirements for each chapter. Before everything, an Internet connection is necessary because many external references will be pointed out as links (URLs) and software will need to be downloaded.

    Also, and even more importantly, you will see that we use the Git versioning system to manage (and work from) the codebase for each chapter. Your local Git repository will correspond to the remote repository for the project (on GitHub), and you will be required to reach out to this remote repository.

    To rephrase the hardware and software list, we will support three operating systems throughout the book: MS Windows, Linux, and Mac OS X.

    For hardware, we recommend a modern, well-equipped workstation with at least 2 GB of RAM and 500 MB of free space on the hard drive.

    Who this book is for

    While writing this book, one of our objectives has been to remain as approachable as possible while providing the widest possible overview of modern web development practices.

    We believed that most of you, with an interest in a cookbook about Spring MVC, are primarily looking for a starter kit and a toolbox to develop modern Spring-based web applications.

    We also believed that most of you would tend to prefer conceptualizing from experience and not from theory. Nowadays, it is clear that people have different mindsets and learning preferences.

    Under this light, chapters will have increasing exigence levels one after the other, from the intuitive Chapter 1, Setup Routine for an Enterprise Spring Application, to the more challenging Chapter 8, Communicating Through WebSockets and STOMP. The initial few chapters will definitely suit a broader audience of Java developers than the final ones.

    Having said this, we have everything in this book! The prerequisites here are mostly pointing to external sources of information. And our showcase application is running and waiting for you to dive into it and understand how things work.

    More generally, we assume you to be a Java developer with prior web experience. Beyond everything, we expect you to have a motivated interest in learning Spring web technologies.

    Sections

    In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

    To give clear instructions on how to complete a recipe, we use these sections as follows:

    Getting ready

    This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

    How to do it…

    This section contains the steps required to follow the recipe.

    How it works…

    This section usually consists of a detailed explanation of what happened in the previous section.

    There's more…

    This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

    See also

    This section provides helpful links to other useful information for the recipe.

    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.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We are going to review the configuration changes applied to the cloudstreetmarket-api webapp in order to set up a type conversion.

    A block of code is set as follows:

    conversionService class=org.sfw.format.support.FormattingConversionServiceFactoryBean>

      converters>

       

          edu.zc.csm.core. converters.StringToStockProduct/>

       

     

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Then select Add and Remove… from the right-click menu.

    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 <feedback@packtpub.com>, 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

    Enjoying the preview?
    Page 1 of 1