40,81 €
Become efficient in both frontend and backend web development with Spring and Vue
Key Features
Book Description
Building Applications with Spring 5 and Vue.js 2, with its practical approach, helps you become a full-stack web developer. As well as knowing how to write frontend and backend code, a developer has to tackle all problems encountered in the application development life cycle – starting from the simple idea of an application, to the UI and technical designs, and all the way to implementation, testing, production deployment, and monitoring.
With the help of this book, you'll get to grips with Spring 5 and Vue.js 2 as you learn how to develop a web application. From the initial structuring to full deployment, you'll be guided at every step of developing a web application from scratch with Vue.js 2 and Spring 5. You'll learn how to create different components of your application as you progress through each chapter, followed by exploring different tools in these frameworks to expedite your development cycle.
By the end of this book, you'll have gained a complete understanding of the key design patterns and best practices that underpin professional full-stack web development.
What you will learn
Who this book is for
Building Applications with Spring 5.0 and Vue.js 2.0 is for you if you are developer who is new to Vue.js or Spring. It is assumed that you have some knowledge of HTML, CSS, and Java.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 673
Veröffentlichungsjahr: 2018
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Zeeyan PinheiroTechnical Editor: Gaurav GalaCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics: Alishon MendonsaProduction Coordinator: Nilesh Mohite
First published: October 2018
Production reference: 1251018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-696-8
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.packt.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.packt.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.
James J. Ye is an experienced software engineer and architect with a particular interest in full-stack engineering. James works at 6Connex Inc. as VP of Engineering. He manages the offshore engineering team in Suzhou, China. The team is responsible for all the engineering of the Virtual Experience SaaS platform. He has been using Spring since version 2.5.x and Vue.js since version 1.0. He also likes Angular, React, TypeScript, and Python.
Vladimir Stanković is an independent software engineer, focused on designing lightweight solutions. He has helped various start-ups and enterprises to develop, scale, and perfect their products utilizing the agile methodology. While working in the healthcare industry, he has obtained hands-on experience with standards such as HIPAA, HL7, and FHIR. Kotlin is his weapon of choice when creating clean and expressive code that's easy to understand and maintain. In his spare time, he runs a blog (svlada) and maintains a community newsletter on microservices (microservicesweekly) for others to use and learn from.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Building Applications with Spring 5 and Vue.js 2
Dedication
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Modern Web Application Development - This Is a New Era
Introduction
JavaScript from a Java developer's viewpoint
Functions and methods
Objects and classes
Objects, properties, and property attributes
Prototype and inheritance
Scope and closure
The this keyword
Hoisting
ES6 basics
Block scoping, let, and const
Classes
Enhanced object literals
Arrow functions
No lexical this
No prototype object
Default parameter value
Rest parameters
Spread syntax
Destructuring assignment
Object destructuring
Array destructuring
Nested destructuring
Rest elements
Function parameters destructuring
Template literals
Modules
Export
Import
Promises
Summary
Vue.js 2 - It Works in the Way You Expected
Fundamental concepts
Vue instance
Components
Vue instance life cycle
Directives
Filters
Mixins
Plugins
Behind the scene
Reactivity system
Summary
Spring 5 - The Right Stack for the Job at Hand
Spring IoC and dependency injection
Spin up the Spring container
Annotation-based configuration
Bean declaration
Dependency injection
Constructor-based injection
Setter-based/method-based injection
Field-based injection
Best practices of dependency injection
Spring MVC
Java EE Servlet
DispatcherServlet
Views
Filters
Spring JDBC and JPA
JDBC driver
Spring JDBC
Hibernate
Spring AOP
Concerns
Aspects
Join points
Advices
Pointcuts
AOP proxy
Weaving
@SecurityCheck
AOP execution flow
Spring transaction management
PlatformTransactionManager
Declarative transaction management
Spring Boot
Starters
Autoconfiguration
Put it together
Place code together
Add APIs
HTTP client – axios
Package app.messages
Summary
TaskAgile - A Trello-like Task Management Tool
Managing requirements in an Agile way
Levels of requirements
Writing a requirement in an Agile project
Writing effective user stories
Tips on writing user stories
TaskAgile user stories
Users
Teams
Boards
Card Lists
Cards
Creating wireframes
Understanding Agile
The Agile manifesto
Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
Full-stack developer skillsets
Requirement analyzing
Communication
Wireframes creating
Data modeling
API designing
Frontend coding
Backend coding
Unit tests and automation tests
Continuous integration
Server monitoring and architecture awareness
Summary
Data Modeling - Designing the Foundation of the Application
Introduction to data modeling
Data modeling stages and deliverables
Conceptual data modeling
Logical data modeling
Physical data modeling
Terminologies used in data modeling
Entities
Attributes
Relationships
Primary keys
Foreign keys
Goals of data modeling
Completeness
Minimal redundancy
Extensibility
Consistency
Conceptual data modeling with ER diagrams
Crow's foot notation
The naming convention
TaskAgile conceptual data models
Subtypes and supertypes
Logical data modeling
Physical data modeling for RDBMS
The naming convention
Physical data modeling for MongoDB
Summary
Code Design - Designing for Stability and Extensibility
Agile code design
What is code design?
Traditional angle
A second angle
Differences between the two angles
Levels of code design
Architecture level
Abstraction level
Implementation level
Devil in the details
Symptoms of bad design
Rigidity
Fragility
Opacity
Immobility
Viscosity
Agile code design practices
Architecture level
Abstraction level
Implementation level
Design principles and design patterns
SOLID design principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)
TaskAgile code design
Layered architecture
Hexagonal architecture
Summary
RESTful API Design - Building Language Between Frontend and Backend
RESTful API characteristics
REST architectural constraints
Client-server
Stateless
Cache
Uniform interface
Layered system
Code-on-demand (optional)
RESTful interface constraints
Identifications of resources
Manipulation of resources through representations
Self-descriptive messages
Hypermedia as the engine of the application state
Opinionated RESTful API
Richardson Maturity Model
Level zero
Level one
Level two
Level three
HATEOAS or not?
What is HATEOAS?
Why you won't need HATEOAS?
Opinionated RESTful API characteristics
Resource-centric
Identifiable through URIs
Defining operations via HTTP methods
Use of HTTP status codes
Versioning
Stateless
Pagination
Searching and sorting
Security
RESTful API design procedure
Finding out the requirements
Identifying resources
Fleshing out API details 
RESTful API implementation in Spring MVC
MVC annotations
Spring HATEOAS
Spring REST Docs
RESTful API consuming
HTTP client
Server-side consuming
RESTful API testing
Unit testing of the Messages App
Summary
Creating the Application Scaffold - Taking off Like a Rocket
Setting up the development environment
Creating the backend scaffold with Spring Initializr
File structure
Committing and pushing
Running the application
Creating the frontend scaffold
File structure
Cleaning up and reorganizing
Didn't we miss something?
Putting two ends together
Building with a single command
Bridging the communication
Introducing vue-router
Spring MVC request mapping
Fixes at the end
Summary
Forms and Validation - Starting with the Register Page
Building a UI with Bootstrap 4
Install and use Bootstrap
Implement the UI of the register page
Create layout diagram
TDD of the register page
Implement the UI
Build registration forms with Vue.js
Write test code for the form
Implement the form bindings
Handle form submit
Test the submitForm() method
Implement the submitForm() method
Communicate with the backend
Test the register() method 
Implement the register() method
Validation on the frontend
Test the data validation
Validate form data with Vuelidate
Improve the tests
Validation on the backend
Creating RegistrationPayload
Create RegistrationPayloadTests
Create RegistrationPayload
Create RegistrationApiController
Create RegistrationApiControllerTests
Implement RegistrationApiController and its dependencies
Implement registration in domain model
Implement the UserService application service
Create UserServiceImplTests
Create MailManager
Build domain events
Implement the UserServiceImpl class
Implement RegistrationManagement
Create RegistrationManagementTests
Implement the RegistrationManagement class
Implement RegistrationManagement dependencies
Implement UserRepository
Create HibernateUserRepositoryTests
Implement HibernateUserRepository
Fixes at the end
Summary
Spring Security - Making Our Application Secure
How to secure a web application
Authenticating users
Single Sign-On
OAuth 2.0
Authorizing users
Preventing attacks
Introducing Spring Security
Spring Security core concepts
Spring Security deep dive
Setting up Spring Security
Spring Security filter chain
Spring Security in action
Unauthenticated request on public resource
Unauthenticated request on protected resource
Spring Security authentication in depth
SecurityContextPersistenceFilter
UsernamePasswordAuthenticationFilter
Spring Security authorization in depth
FilterSecurityInterceptor
Method security 
Building the login page
Implementing the login page UI
Implementing PasswordEncryptorDelegate
Implementing authentication in the backend
Implementing AuthenticationFilter
Implementing UserDetailsService
Implementing UserDetails
Updating SecurityConfiguration
Sending emails using JavaMail
MailManager and its dependencies
Testing DefaultMailManager
Implementing DefaultMailManager
Implementing AsyncMailer
Application properties
Performing end-to-end integration tests
Correcting the port
Using Page Objects
Autogenerating user test data
Testing in specific order
Fixes at the end
Summary
State Management and i18n - Building a Home Page
State management with Vuex
Drawbacks of traditional state management
Modern state management
Vuex in a nutshell
Building home page frontend
UI of the home page
Home page layout and components
Data structure and state management
Backend APIs
Creating a personal board API
Creating the team API
Creating team board API
A combined API to get the user's name, boards, and teams
Implementing home page frontend
Implementing the services and Vuex store
Implementing popup windows with Bootstrap modal
Building the home page backend
Domain models
API handlers
Application services
Repositories and the generic save() method
Adding i18n support with Vue-i18n
Logging SQL queries and performance tuning
Fixes at the end
Summary
Flexbox Layout and Real-Time Updates with WebSocket - Creating Boards
Building the frontend of the board page
The UI of the board page
The layout of the board page
Designing the overall layout
Implementing drag and drop
Building the backend of the board page
APIs for the board page
Changing positions in batch
Implementing real-time updates with WebSocket
Introduction to SockJS
Introduction to Spring WebSocket
The channel-based communication pattern
Frontend implementation of the real-time client
Authenticating a real-time client with JWT
Server implementation of channel handlers
Fixes at the end
Summary
File Processing and Scalability - Playing with Cards
Building the frontend of the card modal
The UI of the card modal window
The layout of the card modal window
Router for board URL and card URL
Implement auto-resize of card title editing
Implementing support of the Markdown format
Implementing file uploads
Building the backend of the card modal
APIs for the card modal
Get card API
Change card title API
Change card description API
Add comment API
Get activities API
Add attachment API
Get attachments API
Saving the uploaded file
Generating thumbnails for images
Storing files to S3
Tracking activity asynchronously with AMQP
Adding card cover images and activity tracking
Fixes at the end
Summary
Health Checking, System Monitoring - Getting Ready for Production
Installing as a service
Spring Profile
The dev profile
The test profile
The end-to-end test profile
The staging and production profile
Spring Boot Actuator
The health endpoint
The info endpoint
The metrics endpoint
The environment endpoint
Endpoint security
Using a different port and firewall
Using the same port and Spring Security
Using a custom filter
Monitoring with Icinga 2
Fixes at the end
Summary
Deploying to the Cloud with Jenkins - Ship It Continuously
Continuous delivery
Registration API integration test
Maturity and cost
Refactoring E2E tests
Running E2E tests during the writing
Running E2E tests before pushing the code to VCS
Run E2E tests after deploying to staging
Last fix before rolling out
Let's ship it
Preparing a Dockerfile
Preparing a Jenkinsfile
Server preparation
Installing MySQL
Installing RabbitMQ
Installing NGINX and the SSL certificate
Building with Jenkins
Summary
Further reading
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book covers the full set of technologies that you need to know about to become a full-stack web developer with Spring and Vue.js. Spring is the most widely used framework for Java programming, and with its latest update to version 5, the framework has undergone some massive changes. Spring supports MVC architectural stylesand is the most popular framework of its kind. Along with Spring in this stack, we will use Vue.js. Vue.js is a lightweight JavaScript framework. Since its release, it has managed to establish itself as one of the most popular frameworks for building user interfaces and is seeing a rapid adoption rate. In this book, you'll become familiar with these technologies while learning to develop a practical web application. You'll discover each technology in the full stack as you build an application up, one layer at a time, just as you'd do in a real project. From initial structuring to full deployment, this book provides step-by-step guidance for developing a web application from scratch with Vue.js and Spring. This book takes a very practical approach to becoming a full-stack web developer. You will create the different components of your application as you progress through each chapter. You will walk through the different tools in each of these frameworks to expedite your development cycle. Finally, this book will also demonstrate the key design patterns and best practices that underpin professional full-stack web development.
This book is for developers who want to learn full-stack web application development with Spring Framework 5 and Vue.js 2. It introduces you to the full set of technologies and tools that you need for developing a practical web application. It doesn't assume that you have any prior knowledge of Vue.js or Spring Framework. However, you will be better prepared if you have some basic experience with HTML, CSS, and JavaScript on the frontend side, and the Java language, servlets, and JDBC on the server side.
Chapter 1, Modern Web Application Development - This Is a New Era, introduces JavaScript from a Java developer's perspective by highlighting the parts that confuse Java developers the most. It also introduces the basics of ES6.
Chapter 2, Vue.js 2 - It Works in the Way You Expected, introduces all aspects of Vue.js 2, from its fundamental concepts to its internal reactivity system.
Chapter 3, Spring 5 - The Right Stack for the Job at Hand, introduces the major features of Spring Framework 5, including Inversion of Control (IoC) and dependency injection, Spring MVC, Spring JDBC, JPA, Spring AOP, transaction management, and Spring Boot.
Chapter 4, TaskAgile - A Trello-like Task Management Tool, introduces requirement management in an Agile project, user story writing, and wireframe creation. It also discusses the Agile methodology and the skill sets a full-stack developer should have.
Chapter 5, Data Modeling - Designing the Foundation of the Application, introduces data modeling, the goal of data modeling, and the three stages of data modeling: from conceptual data modeling to logical data modeling, and then to physical data modeling.
Chapter 6, Code Design - Designing for Stability and Extensibility, introduces Agile code design, design principles, and design patterns. It also discusses the code design of TaskAgile applications.
Chapter 7, RESTful API Design - Building Language Between Frontend and Backend, introduces RESTful API characteristics, RESTful API design procedure, the implementation of Spring MVC, API consumption, and API testing.
Chapter 8, Creating the Application Scaffold - Taking off Like a Rocket, introduces how to create an application scaffold with Spring Initializr and vue-cli, as well as how to put these two ends together.
Chapter 9, Forms and Validation - Starting with the Register Page, is a step-by-step tutorial on how to create the register page of a TaskAgile application, from the frontend to the backend, including unit tests at both ends.
Chapter 10, Spring Security - Making Our Application Secure, is a step-by-step tutorial on how to create the login page of a TaskAgile application, from the frontend to the backend, including end-to-end testing of the register page and the login page.
Chapter 11, State Management and i18n - Building a Home Page, is a step-by-step tutorial on how to create the home page of a TaskAgile application, covering the use of Vuex and the implementation of i18n.
Chapter 12, Flexbox Layout and Real-Time Updates with WebSocket - Creating Boards, is a step-by-step tutorial on how to create a boards-based UI by using Flexbox, as well as how to implement real-time updates with WebSocket.
Chapter 13, File Processing and Scalability - Playing with Cards, is a tutorial on the implementation of cards on the boards page. It focuses on file processing and the use of the message queue.
Chapter 14, Health Checking, System Monitoring - Getting Ready for Production, focuses on the use of Spring Profile and Spring Boot Actuator to prepare for application release.
Chapter 15, Deploying to the Cloud with Jenkins - Ship It Continuously, introduces continuous delivery, the creation of API integration tests, and the use of Jenkins and Docker to ship an application.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
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/Building-Applications-with-Spring-5-and-Vue.js-2. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788836968_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
The diversity of the modern web application development ecosystem is increasing at anastonishing rate. You can see new frameworks and libraries coming out almost every day. People seem to be happy with constantly reinventing the wheel. This could be daunting to new learners as the time it takes to master a new skill makes it sometimes difficult to keep pace with the rate with which technologies are evolving. And this has caused frequent complaints of making web development unnecessarily complicated, as there are many new libraries and frameworks to learn and a large number of new tools to familiarize yourself with.
The anxiety associated with the feeling that you might not be able to keep up with the mainstream can be released once you have learned how to create a full-stack modern web application and master the skill sets that are required to build such an application. And, with this book, you will learn these skill sets and realize that being a full-stack developer is not only about knowing how to write frontend and backend code. In this book, we will create a real-world, full-stack web application and cover most of the skills that a full-stack developer would require. And once you have finished reading it, you will understand that languages and frameworks are just tools in your toolbox. You can replace them with other languages and frameworks and also build great full-stack applications.
To start our journey, we will begin with the basics. Once you have those basics imprinted in your mind, you can learn the frameworks more efficiently. In this chapter, we will cover the following topics:
An introduction to the full-stack web application we will build in this book
Learning JavaScript from a Java developer's viewpoint
Learning the features of ECMAScript 2015 that we will use in this book
If you're creating a résumé page for your personal website, it will most likely be sufficient to write it in vanilla JavaScript, HTML 5, and some creative CSS style sheets that make it look special and unique. And if you're creating the jobs page of your company's official website, doing it barehanded might work. But if you use a number of frameworks to style the page and to process logic and animations, you will find yourself in a much better position that you can still go home from work earlier than usual and enjoy a cup of coffee with friends at the weekend. And if you're building something like Monster (https://www.monster.com/) I hope that you are not just carrying those favorite frameworks with you to the battlefield, and if you go barehanded, you wouldn't even make it there. With the level of complexity of such an application and the fact that you will need to keep improving or changing features because of the neverending stop-change requirements, you need to bring the tools for modern web application development with you.
In this book, we will create a modern web application called TaskAgile, which is a Trello-like application for task management. Let's first get an overview of the technologies that we will use to build it.
For the frontend, we will use Vue.js 2 as our frontend application framework, Bootstrap 4 as the UI framework, and we will write our frontend in ES6, also known as ECMAScript 2015, or ES 2015, and then use Babel to compile it into ES5 code. We will use ESLint to check our JS code to make sure it follows all the rules we defined and use Flow (https://flow.org) for static type checking. We will use Jest to write our frontend unit testing's and use Nightwatch.js to run our end-to-end test cases. We will use webpack 4 to bundle all the dependencies and use npm to take care of the package management.
For the backend, we will use Spring Boot 2 to create a Spring 5 application. And we will use Hibernate 5 as our object-relational mapping (ORM) framework, and MySQL as our database. We will use Spring Security for authentication and authorization, and we will implement a real-time-update feature with Spring WebSocket. We will use Spring AMPQ for asynchronously processing background tasks and Spring Session for server-side session management.
Now, before we introduce Vue.js 2 and Spring 5, for readers who are not familiar with JavaScript, let's learn the basics of it, starting with the part that Java developers would easily get confused with.
For readers who are new to JavaScript but who are familiar with the Java language, here are some differences between the two languages that may confuse you. And even though this section is written from a Java developer's perspective, if you're new to JavaScript, you will also find it informative.
