What is Spring MVC?
Spring MVC is a framework for creating loosely coupled web applications that separates the main aspects of their development: objects, business logic, and program appearance. The main advantage of the MVC architecture is the ability to change one of the application components without significantly affecting the rest.
The model contains application data. Usually includes POJO classes (Plain Old Java Objects) – plain old Java objects or, in other words, beans.
Representation or view. Used to visualize and display application data using a user interface. Responsible for how the model data will look in the user’s browser.
Controller. The controller is needed to process user requests and call back-end services. It structures the request, creates an appropriate model for further display in the browser.
DispatcherServletThe Dispatcher Servlet is the heart of Spring Web MVC, a fully customizable front controller that coordinates all request processing activities.Request lifecycle
As we have already figured out, the Spring MVC Framework is logically built around the DispatcherServlet front controller that handles all HTTP requests and responses.
The principle of its work
- The DispatcherServlet front controller receives the request.
- The DispatcherServlet passes this request to a HandlerMapping , an interface implemented by objects that define the mapping between requests to find the appropriate controller.
- HandlerMapping sends the controller information back to the DispatcherServlet.
- The DispatcherServlet invokes the controller previously identified via HandlerMapping. The selected controller processes the request by calling the appropriate method to prepare the data and creating some business logic (or fetching the information directly from the database).
- The controller returns the necessary model data and UI information to DispatcherServlet to select the appearance of their display.
- As soon as the DispatcherServlet receives the ModelAndView object, it passes it to the ViewResolver – an interface that can find (resolve) a view by its name (View Name), in order to then find the corresponding View display option.
- Having made a choice, ViewResolver sends the necessary information back to the front controller.
- The DispatcherServlet calls the appropriate View (defined by the ViewResolver).
- View generates an HTML response and sends it back.
- Finally, the main controller provides instructions to the browser to customize the given HTML and then display the result to the end user.
Steps to Implement an MVC Spring Web Application Using Java Configuration
- Initially, we need to create a POM.XML file containing the maven dependencies from the Spring framework.
The project must contain a web.xml file that receives all requests from the client. In our case, instead of web.xml, we will use WebInitializer.java. The getServletMappings() function accepts all requests that match a ‘/’ URL mapping.
- The getServletConfigClasses() function configures the MVCconfig.java file, which we will use instead of the dispatcher servlet for java configuration. This class extends the AbstractAnotationConfigDispatcherServletInitializer class and serves the purposes we previously defined in the web.xml file.
- Now we need to create the MVCconfig.java file. As mentioned above, we will use it instead of DispatcherServlet. Annotating a class with @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.
- To enable auto-detection of annotated controllers, you must add component scanning to the configuration. It also gives the path to the base package (eg today.highload.web) in which to look for the controller files. This class extends the WebMvcConfigurerAdapter class to serve the dispatcher servlet.
- Now we need to define the controller. Controllers interpret user input and transform it into a model.
@RequestMapping style annotations are used to map a URL (eg /GREET for an entire class) or a specific handler method. Let’s create an object of the ModelAndView class, where setViewName() specifies the display of information to call, and addObject() specifies the dynamic content to be added to this object.
- We now need to create an index.jsp index page for the application that is displayed when the user navigates to the given URL.
- Clicking the welcome button from the above index.jsp opens the Result.jsp page, which we need to predefine.
Defining a Controller
The @Controller annotation says that the class is a Spring MVC controller. The @RequestMapping annotation is needed for mapping (binding) to the URL of a class or a specific handler method.
Moreover, in the first case, it informs us about the ownership of all methods in the controller in question, specifically, to the “/Welcome” URL. In the second case, we use @RequestMapping to declare the printWelcome() method, defining it as the default method for handling HTTP requests.
View creation (JSP)
Using the Spring MVC framework, you can display a page in dozens of different formats, including JSP, HTML, PDF, Excel, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports, and others. However, JSP templates written with JSTL are the most commonly used.Benefits of Spring MVC
Putting it all together, let’s summarize:
Lightweight: Since Spring is a lightweight framework, there will be no performance issues in a Spring-based web application.
High Productivity: Spring MVC can speed up any development process.
Security: Most online banking web applications are developed using Spring MVC, which benefits from built-in Spring Security, a great API for implementing enterprise-grade security.
The MVC pattern is supported, so it’s a great way to develop modular web applications.
Spring MVC also implements all the core core features of the Spring Framework, including the popular Inversion of Control (inversion of control) and Dependency Injection (dependency injection).
An example implementation of the Spring MVC framework
To thoroughly understand the concept under consideration, I suggest that you familiarize yourself with examples of the implementation of the framework from publicly available sources:
- A basic example of the implementation of the Hello World program in Spring 4 (XML configuration).
- Spring vs Java EE.
Let’s do a little comparison of two key Java web developer stacks: Spring and Java EE.
Like Spring, Java EE includes additional libraries for database access (JDBC, JPA), remote machine invocation (RMI), informing (JMS), web administration, XML processing, and provides standard APIs for enterprise JavaBeans, portlets, Servlets, Java Server Pages, etc.
The fundamental goal of Java EE is to unravel the major problems developers face with regards to building current applications with various APIs.
At the same time, Java EE development has a high level of complexity, which raises an unreasonably high bar, not only for beginners. And it can be difficult for experienced specialists to understand the already written functionality, so development in Java EE takes longer and, accordingly, more expensive.
Spring is an open source framework for Java for large businesses.
The Spring framework aims to provide the simplest implementation of J2EE ideas and great programming practices by extending the capabilities of the POJO-based programming model.
Those. Java EE is more of an official standard, while Spring is more of a framework that implements this standard in its own way.
It is a core module that provides a comprehensive programming and configuration model for modern Java-based enterprise applications – on any deployment platform.
- It contains a lot of core (core) Spring technologies:
- core – basic functionality that implements the concepts of IoC (inversion of control) and DI (dependency injection);
- AOP – Aspect-Oriented Programming – aspect-oriented programming aimed at implementing end-to-end logic;
- MVC and WebFlux are frameworks for web interaction;
- JDBC, ORM – technologies for interacting with databases;
- Test – functionality for transparent, uncomplicated testing of Spring container data;
- SpEL – Spring Expression Language – Spring expression language;
- spring boot
Simplifies the creation of Spring-based applications by minimizing the initial configuration of the application and auto-configuring elements of the application on Spring.
Significantly simplifies the use of data access technologies, relational and non-relational databases (removes repetitive code and simplifies interaction with data). This article is a good tutorial on connecting Spring Data.
It is used in microservice architecture, simplifying the interaction of microservices with each other and automating the deployment of applications on cloud platforms such as AWS, Azure, etc.
Provides a powerful and customizable tool for authentication (authentication) and access control (authorization) to the application.
This module provides support for Spring applications built with GraphQL Java.GraphQL is a query language for APIs that allows clients to query the limited amount of data they need, which in turn allows them to collect data in a limited number of requests. If you’re already familiar with JPA, you’ve probably already come across EntityGraph, with a similar (or the same) concept.
This part of the Spring framework provides APIs and implementations for managing user session information (user session data is stored in persistent storage like Redis, MongoDb, HazelCast, etc.).
This module is designed to facilitate messaging in Spring-based applications and support integration with external systems through declarative adapters.These adapters provide a higher level of abstraction than Spring’s support for remoting, messaging, and scheduling.
Provides a rich set of tools to simplify REST API development: tools for routing requests, for converting JSON/XML into objects of required types, etc.
Spring Web Flow
Spring Web Flow is based on Spring MVC and allows you to implement “flows” of a web application. Such flows encapsulate a series of steps that guide the user through the execution of some business task.They span multiple HTTP requests, are stateful, operate on transactional data, are reusable, and can be dynamic and long-lived in nature.
Spring WebServicesThis module is designed to facilitate the development of SOAP services based on contracts, allowing you to create flexible web services using one of the many ways to manipulate XML payloads.SOAP – Simple Object Access Protocol – A simple protocol for accessing objects.
The module provides some APIs to make it easier to create REST controllers that follow the HATEOAS principle when working with Spring and especially Spring MVC.
This module provides functionality for batch data processing (when data is processed in large chunks – batches), which are vital for the daily operation of corporate systems.Spring Batch provides reusable features that are needed to handle large volumes of records, including logging/tracing, transaction management, job processing statistics, job restarting, skipping, and resource management.
The module applies core Spring concepts to developing AMQP based messaging solutions. It provides a template as a high-level abstraction for sending and receiving messages. It also provides support for message-driven POJOs with a listener container.
Spring for Apache Kafka
This project applies the core concepts of Spring to developing messaging solutions based on Kafka.A template is provided as a high-level abstraction for sending messages. It also provides support for message-driven POJOs with the necessary annotations and a listener container.There is clearly a similarity with Spring AMQP, but this module is adapted specifically for Kafka.
Provides client-side support for storing, retrieving, and deleting credentials from a CredHub server running on the Cloud Foundry platform.CredHub – Provides an API for securely storing, creating, retrieving, and deleting credentials of various types.Spring CredHub provides a Java binding for the CredHub API, making it easy to integrate Spring applications with CredHub.
This module allows application developers to use state machine concepts with Spring applications.
Spring Vault provides familiar Spring abstractions and client-side support for accessing, storing, and revoking secrets. It offers both low-level and high-level abstractions for interacting with Vault, freeing the user from infrastructure concerns.
The library makes it easy to build a fully functional shell application (also known as command line) by relying on Spring Shell jars and adding your own commands (which come as methods in Spring beans).Creating a command line application can be useful, for example, for interacting with your project’s REST API or for working with local file content.
This module provides a RAD tool that can create and manage your Spring-based application.Its purpose is to improve the productivity of Java developers. It can’t write your application’s business logic, but it can handle configuration and infrastructure stuff.
This library simplifies LDAP operations and is based on the Spring JdbcTemplate. The framework allows you to search and close the context, view results, encode / decode values, filters and much more (built on the same principles as Spring Jdbc).