Spring MVC Cookbook

Book description

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.

Table of contents

  1. Spring MVC Cookbook
    1. Table of Contents
    2. Spring MVC Cookbook
    3. Credits
    4. About the Author
    5. About the Reviewer
    6. www.PacktPub.com
      1. eBooks, discount offers, and more
        1. Why Subscribe?
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Sections
        1. Getting ready
        2. How to do it…
        3. How it works…
        4. There's more…
        5. See also
      5. Conventions
      6. Reader feedback
      7. The showcase application: CloudStreet Market
      8. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    8. 1. Setup Routine for an Enterprise Spring Application
      1. Introduction
        1. Why such a routine?
        2. Why making use of the Eclipse IDE?
        3. Why making use of Maven?
        4. What does the Spring Framework bring?
      2. Installing Eclipse for JEE Developers and Java SE 8
        1. Getting ready
        2. How to do it...
        3. How it works…
          1. Eclipse for Java EE developers
          2. Choosing a JVM
          3. Java SE 8
      3. Configuring Eclipse for Java 8, Maven 3, and Tomcat 8
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. The eclipse.ini file
          2. Setting the –vm option
          3. Customizing JVM arguments
          4. Changing the JDK compliance level
          5. Configuring Maven
          6. A repository manager
          7. Tomcat 8 inside Eclipse
        4. There's more...
      4. Defining the project structure with Maven
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. New Maven project, new Maven module
          2. The standard project hierarchy
          3. The project's structure in the IDE
          4. Maven's build life cycles
            1. The clean life cycle
            2. The default life cycle
            3. Plugin goals
            4. Built-in life cycle bindings
            5. About Maven commands
        4. There's more...
          1. How did we choose the jar module's name?
          2. How did we choose the names for deployable modules?
          3. Why did we create core modules?
        5. See also...
      5. Installing Spring, Spring MVC, and a web structure
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Inheritance of Maven dependencies
            1. Basic inheritance
            2. Managed inheritance
          2. Including third-party dependencies
            1. The Spring Framework dependency model
            2. The Spring MVC dependency
            3. Using Maven properties
          3. The web resources
            1. The target runtime environment
            2. The Spring web application context
            3. Plugins
              1. The Maven compiler plugin
              2. The Maven surefire plugin
              3. The Maven enforcer plugin
              4. The Maven war plugin
        4. There's more...
        5. See also
          1. The Maven checkstyle plugin
    9. 2. Designing a Microservice Architecture with Spring MVC
      1. Introduction
        1. The User eXperience paradigm
        2. Microservice architectures
      2. Configuring a controller with simple URL mapping
        1. Getting ready
        2. How to do it...
          1. Downloading and installing GIT
          2. Configuring GIT in Eclipse
        3. How it works...
          1. Spring MVC overview
            1. Front controller
            2. MVC design pattern
            3. Spring MVC flow
          2. DispatcherServlet – the Spring MVC entrypoint
          3. Annotation-defined controllers
            1. @Controller
            2. @RequestMapping
          4. Controller method-handler signatures
            1. Supported method arguments types
            2. Supported annotations for method arguments
            3. Supported return Types
        4. There's more...
      3. Configuring a fallback controller using ViewResolver
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. URI template patterns
            1. Ant-style path patterns
            2. Path pattern comparison
            3. ViewResolvers
        4. There's more...
          1. @PathVariable to read variables in URI template patterns
      4. Setting up and customizing a responsive single page webdesign with Bootstrap
        1. Getting ready
        2. How to do it...
          1. Installing a Bootstrap theme
          2. Customising a Bootstrap theme
          3. Creating responsive content
        3. How it works...
          1. The theme installation
          2. Bootstrap highlights
            1. Bootstrap scaffolding
              1. Grid system and responsive design
              2. Defining columns
              3. Offsetting and nesting
              4. Fluid gridding
            2. Bootstrap CSS utilities
              1. Uniform Buttons
              2. Icons
              3. Tables
            3. Bootstrap components
              1. Navbars
              2. Hero units
              3. Alerts
              4. Badges and labels
        4. There's more...
        5. See also
      5. Displaying a model in the View, using the JSTL
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. The approach to handle our data
            1. Injection of services via interfaces
            2. How does Spring choose the dummy implementations?
            3. DTOs to be used in View layer
            4. Dummy service implementations
          2. Populating the Model in the controller
          3. Rendering variables with the JSP EL
            1. Implicit objects
          4. Rendering variables with the JSTL
            1. Taglib directives in JSPs
        4. There's more...
          1. More about JSP EL
          2. More about the JavaBeans standard
          3. More about the JSTL
      6. Defining a common WebContentInterceptor
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Common behaviors for Controllers
          2. Global session control
            1. Requiring sessions
            2. Synchronizing sessions
          3. Cache-header management
          4. HTTP method support
          5. A high-level interceptor
          6. Request lifecycle
        4. There is more...
          1. More features offered by WebContentGenerator
        5. See also...
          1. Web caching
          2. New support classes for @RequestMapping since Spring MVC 3.1
      7. Designing a client-side MVC pattern with AngularJS
        1. Getting ready
        2. How to do it...
          1. Setting up the DOM and creating modules
          2. Defining the module's components
        3. How it works...
          1. One app per HTML document
            1. Module autobootstrap
            2. Manual module bootstrap
          2. AngularJS Controllers
            1. Bidirectional DOM-scope binding
          3. AngularJS directives
            1. ng-repeat
            2. ng-if
          4. AngularJS factories
            1. Dependency injection
        4. There's more...
    10. 3. Working with Java Persistence and Entities
      1. Introduction
        1. The Entities' benefits
        2. The Entity manager and its persistence context
      2. Configuring the Java Persistence API in Spring
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. The Spring-managed DataSource bean
          2. The EntityManagerFactory bean and its persistence unit
          3. The Spring Data JPA configuration
        4. See also
      3. Defining useful EJB3 entities and relationships
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Entity requirements
          2. Mapping the schema
            1. Mapping tables
            2. Mapping columns
            3. Annotating fields or getters
            4. Mapping primary keys
            5. Identifier generation
          3. Defining inheritance
            1. The single-table strategy
            2. The table-per-class strategy
          4. Defining relationships
            1. How relationships between entities have been chosen
        4. There's more...
          1. The FetchType attribute
          2. The Cascade attribute
        5. See also
      4. Making use of the JPA and Spring Data JPA
        1. How to do it...
        2. How it works...
          1. Injecting an EntityManager instance
          2. Using JPQL
          3. Reducing boilerplate code with Spring Data JPA
            1. Query creation
            2. Persisting Entities
        3. There's more...
          1. Using native SQL queries
          2. Transactions
        4. See also
    11. 4. Building a REST API for a Stateless Architecture
      1. Introduction
        1. A definition of REST
        2. RESTful CloudStreetMarket
      2. Binding requests and marshalling responses
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. A super RequestMappingHandlerAdapter bean
            1. Broad support for @RequestMapping annotations
              1. setMessageConverters
              2. setCustomArgumentResolvers
              3. setWebBindingInitializer
            2. The ConversionService API
            3. Choosing between PropertyEditors or converters
        4. There's more...
          1. Built-in PropertyEditor implementations
          2. The Spring IO reference document
      3. Configuring content-negotiation (JSON, XML, and so on)
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Support for XML marshalling
            1. The XStream marshaller
          2. Negotiation strategies with ContentNegotiationManager
            1. The Accept header
            2. The file extension suffix in the URL path
            3. The request parameter
            4. Java Activation Framework
          3. @RequestMapping annotations as ultimate filters
        4. There's more...
          1. Using a JAXB2 implementation as an XML parser
          2. The ContentNegotiationManagerFactoryBean JavaDoc
      4. Adding pagination, filters, and sorting capabilities
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Spring Data pagination support (you will love it!)
            1. Pagination and sorting in repositories
            2. PagingAndSortingRepository<T,ID>
            3. The web part – PageableHandlerMethodArgumentResolver
          2. A useful specification argument resolver
            1. The JPA2 criteria API and Spring Data JPA specifications
            2. SpecificationArgumentResolver
        4. There's more...
          1. Spring Data
          2. Angular routes
        5. See also
          1. Bootstrap pagination with the Angular UI
      5. Handling exceptions globally
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Global exception handling with @ControllerAdvice
            1. The support ResponseEntityExceptionHandler class
            2. A uniform error response object
        4. There's more...
          1. HTTP Status Codes
          2. The official article about exception handling in Spring MVC
          3. JavaDocs
        5. See also
      6. Documenting and exposing an API with Swagger
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. An exposed metadata
          2. The Swagger UI
        4. There's more...
          1. The Swagger.io
          2. The swagger-springmvc documentation
        5. See also
          1. Different tools, different standards
    12. 5. Authenticating with Spring MVC
      1. Introduction
      2. Configuring Apache HTTP to proxy your Tomcat(s)
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. DNS configuration or host aliasing
          2. In production – editing DNS records
          3. An alias for the host
            1. Alias definition for OAuth developments
          4. Apache HTTP configuration
            1. Virtual-hosting
            2. The mod_proxy module
            3. ProxyPassReverse
              1. Workers
            4. The mod_alias module
          5. Tomcat connectors
            1. HTTP connectors
            2. AJP connectors
        4. There is more…
        5. See also
          1. Alternatives to Apache HTTP
      3. Adapting users and roles to Spring Security
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Introduction to Spring Security
          2. ThreadLocal context holders
          3. Noticeable Spring Security interfaces
          4. The Authentication interface
          5. The UserDetails interface
            1. Authentication providers
              1. The UserDetailsManager interface
            2. The GrantedAuthority interface
        4. There is more…
          1. Spring Security reference
            1. Technical overview
            2. Sample applications
            3. Core services
      4. Authenticating over a BASIC scheme
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. The Spring Security namespace
            1. The <http> component
            2. The Spring Security filter-chain
              1. Our <http> configuration
          2. The AuthenticationManager interface
          3. Basic authentication
            1. BasicAuthenticationFilter
              1. With an authenticationEntryPoint
              2. Without an authenticationEntryPoint
        4. There is more…
          1. In the Spring Security reference
          2. The remember-me cookie/feature
      5. Authenticating with a third-party OAuth2 scheme
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. From the application point of view
          2. From the Yahoo! point of view
            1. OAuth2 explicit grant flow
            2. Refresh-token and access-token
          3. Spring social – role and key features
          4. Social connection persistence
          5. Provider-specific configuration
            1. One entry-point – connectionFactoryLocator
            2. Provider-specific ConnectionFactories
            3. Signing in with provider accounts
        4. There is more…
          1. Performing authenticated API calls
          2. The Spring social ConnectController
        5. See also
          1. SocialAuthenticationFilter
          2. The list of Spring social connectors
          3. Implementing an OAuth2 authentication server
          4. The harmonic development blog
      6. Storing credentials in a REST environment
        1. Getting ready
        2. How to do it...
          1. Client side (AngularJS)
          2. Server side
        3. How it works...
          1. Authenticating for Microservices
          2. Using the BASIC authentication
            1. Using OAuth2
          3. HTML5 SessionStorage
          4. SSL/TLS
          5. BCryptPasswordEncoder
        4. There is more…
          1. Setting HTTP headers with AngularJS
          2. Browser support for localStorage
          3. About SSL and TLS
      7. Authorizing on services and controllers
        1. Getting ready
        2. How to do it...
        3. How it works...
          1. Spring Security authorities
          2. Configuration attributes
          3. Pre-invocation handling
            1. AccessDecisionManager
          4. After invocation handling
          5. Expression-based access control
            1. Web Security expressions
            2. Method security expressions
              1. Access control using @PreAuthorize and @PostAuthorize
              2. Filtering collections using @PreFilter and @PostFilter
          6. JSR-250 and legacy method security
        4. There is more…
          1. Domain Object Security (ACLs)
          2. Spring EL
          3. The Spring Security reference
        5. See also
    13. 6. Implementing HATEOAS
      1. Introduction
        1. The Richardson Maturity Model
      2. Turning DTOs into Spring HATEOAS resources
        1. How to do it…
        2. How it works...
          1. Spring HATEOAS resources
            1. The ResourceSupport class
            2. The Resource class
          2. The Identifiable interface
          3. Abstracting the Entities' @Id
        3. There's more…
        4. See also
      3. Building links for a hypermedia-driven API
        1. How to do it…
        2. How it works...
          1. Resource assemblers
          2. PagedResourcesAssembler
          3. Building links
            1. EntityLinks
            2. ControllerLinkBuilder
        3. There's more…
          1. The use of regular expressions in @RequestMapping
        4. See also
      4. Choosing a strategy to expose JPA Entities
        1. How to do it…
        2. How it works...
          1. The REST CRUD principle
          2. Exposing the minimum
            1. If the Entity doesn't own the relationship
            2. If the Entity owns the relationship
          3. Separation of resources
        3. There's more…
          1. Jackson custom serializers
          2. XStream converters
      5. Retrieving data from a third-party API with OAuth
        1. How to do it…
        2. How it works...
          1. Introduction to the financial data of Yahoo!
            1. Graph generation/display
          2. How is the financial data pulled/refreshed?
          3. Calling third-party services
        3. There's more…
          1. Spring Social — existing API providers
        4. See also
    14. 7. Developing CRUD Operations and Validations
      1. Introduction
      2. Extending REST handlers to all HTTP methods
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. HTTP/1.1 specifications – RFC 7231 semantics and content
            1. Basic requirements
            2. Safe and Idempotent methods
            3. Other method-specific constraints
          2. Mapping request payloads with @RequestBody
          3. HttpMessageConverters
            1. Provided HttpMessageConverters
            2. Using MappingJackson2HttpMessageConverter
          4. Using @RequestPart to upload an image
          5. Transaction management
            1. The simplistic approach
        4. There's more…
          1. Transaction management
            1. ACID properties
            2. Global versus local transactions
        5. See also
      3. Validating resources using bean validation support
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. Using Spring validator
            1. ValidationUtils
            2. I18n validation errors
          2. Using JSR-303/JSR-349 Bean Validation
            1. On-field constraint annotations
              1. Implementation-specific constraints
            2. LocalValidator (reusable)
        4. There's more…
          1. ValidationUtils
          2. Grouping constraints
          3. Creating a custom validator
          4. The Spring reference on validation
        5. See also
      4. Internationalizing messages and contents for REST
        1. How to do it…
          1. Backend
          2. Frontend
        2. How it works...
          1. MessageSource beans
            1. ResourceBundleMessageSource
            2. ReloadableResourceBundleMessageSource
            3. StaticMessageSource
          2. Our MessageSource bean definition
          3. Using a LocaleResolver
            1. AcceptHeaderLocaleResolver
            2. FixedLocaleResolver
            3. SessionLocaleResolver
            4. CookieLocaleResolver
        3. There's more…
          1. Translating client-side with angular-translate.js
      5. Validating client-side forms with HTML5 AngularJS
        1. How to do it…
        2. How it works...
          1. Validation-constraints
            1. Required
            2. Minimum/maximum length
            3. Regex pattern
            4. Number/e-mail/URL
          2. Control variables in forms
            1. Modified/Unmodified state
            2. Valid/Invalid state
            3. Errors
          3. Form state transclusions and style
        3. See also
    15. 8. Communicating Through WebSockets and STOMP
      1. Introduction
      2. Streaming social events with STOMP over SockJS
        1. Getting ready
        2. How to do it…
          1. Apache HTTP Proxy configuration
          2. Frontend
          3. Backend
        3. How it works...
          1. An introduction to WebSockets
            1. WebSocket Lifecycle
            2. Two dedicated URI schemes
          2. The STOMP protocol
          3. SockJS
          4. Spring WebSocket support
            1. All-in-one configuration
            2. Defining message handlers via @MessageMapping
          5. Sending a message to dispatch
            1. SimpMessagingTemplate
            2. The @SendTo annotation
        4. There's more…
        5. See also
      3. Using RabbitMQ as a multiprotocol message broker
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. Using a full-featured message broker
            1. Clusterability – RabbitMQ
            2. More STOMP message types
          2. StompMessageBrokerRelay
        4. See also
      4. Stacking and consuming tasks with RabbitMQ and AMQP
        1. Getting ready
        2. How to do it…
          1. Sender side
          2. Consumer side
          3. Client-side
        3. How it works...
          1. Messaging architecture overview
            1. A scalable model
          2. AMQP or JMS?
        4. There's more…
          1. A great introduction to AMQP by pivotal
          2. A better way to publish application events
        5. See also
      5. Securing messages with Spring Session and Redis
        1. Getting ready
        2. How to do it…
          1. Apache HTTP proxy configuration
          2. Redis server installation
          3. MySQL server installation
          4. Application-level changes
          5. RabbitMQ configuration
          6. The results
        3. How it works...
          1. The Redis server
          2. Spring session
            1. SessionRepositoryFilter
              1. RedisConnectionFactory
            2. CookieHttpSessionStrategy
            3. Spring Data Redis and Spring Session Data Redis
          3. The Redis Session manager for Tomcat
          4. Viewing/flushing sessions in Redis
          5. securityContextPersistenceFilter
          6. AbstractSessionWebSocketMessageBrokerConfigurer
          7. AbstractSecurityWebSocketMessageBrokerConfigurer
        4. There's more…
          1. Spring Session
          2. Apache HTTP proxy extra configuration
          3. Spring Data Redis
        5. See also
    16. 9. Testing and Troubleshooting
      1. Introduction
      2. Automating Database Migrations with FlyWay
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. A limited number of commands
            1. Migrate
            2. Clean
            3. Info
            4. Validate
            5. Baseline
            6. Repair
          2. About Flyway Maven plugin
        4. There is more…
          1. The official documentation
        5. See also
      3. Unit testing with Mockito and Maven Surefire
        1. How to do it…
        2. How it works...
          1. @Test annotation
            1. The expected and timeout arguments
          2. The @RunWith annotation
          3. @Before and @After annotations
          4. @BeforeClass and @AfterClass annotations
          5. Using Mockito
            1. MockitoJUnitRunner
            2. The transferCriticalData example
            3. The registerUser example
        3. There is more…
          1. About Mockito
          2. JUnit Rules
        4. See also
      4. Integration testing with Cargo, Rest-assured, and Maven failsafe
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. Maven Failsafe versus Maven Surefire
          2. Code Cargo
            1. Cargo Maven Plugin
              1. Binding to Maven phases
              2. Using an existing Tomcat instance
          3. Rest assured
            1. Static imports
            2. A Given, When, Then approach
        4. There is more…
          1. About Cargo
          2. More REST-assured examples
      5. Injecting Spring Beans into integration tests
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. SpringJUnit4ClassRunner
          2. The @ContextConfiguration annotation
        4. There is more…
          1. JdbcTemplate
          2. Abstraction of boilerplate logic
            1. Extraction of auto-generated IDs
      6. Modern application Logging with Log4j2
        1. Getting ready
        2. How to do it…
        3. How it works...
          1. Apache Log4j2 among other logging frameworks
            1. The case of SLF4j
          2. Migrating to log4j 2
            1. Log4j 2 API and Core
            2. Log4j 2 Adapters
              1. Log4j 1.x API Bridge
              2. Apache Commons Logging Bridge
              3. SLF4J Bridge
              4. Java Util Logging Adapters
              5. Web Servlet Support
          3. Configuration files
        4. There is more…
          1. Automatic configuration
          2. Official documentation
          3. Interesting Redis Appender implementation
    17. Index

Product information

  • Title: Spring MVC Cookbook
  • Author(s): Alex Bretet
  • Release date: February 2016
  • Publisher(s): Packt Publishing
  • ISBN: 9781784396411