The Model-View-Controller (MVC) architecture can be used to create flexible and loosely coupled web applications. This architecture has three components: the model, the view, and the controller. In this topic, we will explore the functionality of each of these components and see how they can be implemented in Spring.
MVC architecture
Let's talk about the components of the MVC architecture. Each of them handles a specific task:
The model holds application data, generally using Java or Kotlin objects.
The view renders model data, generating output the client's browser can display.
The controller is responsible for processing user requests, building a model, and passing it to the view for rendering.
In Spring, the MVC architecture is designed using a component known as a DispatcherServlet. The diagram below outlines the whole process completed by a DispatcherServlet.
The DispatcherServlet will receive HTTP requests to be processed. It will then use a component called HandlerMapping to call the appropriate controller for the request. The HandlerMapping is implemented in the web.xml file and provides the mapping from URL patterns to their required controllers. Once the handler mapping is completed, the Controller will handle the request.
The Controller will take the request and process it as required. It will also set the model data and return the view name to be processed by the DispatcherServlet. The Controller component is defined in our program using the @Controller annotation. To map values from the model to the view, the Controller will typically use a ModelMap object. You can use the addAttribute method of this object to map variables in the model to values in the view.
Once the Controller completes its work, the DispatcherServlet will utilize a component called ViewResolver to get the required view from the name returned from the controller. Once the view is retrieved, the DispatcherServlet will pass the model data to the View and return it to the requester to be rendered in the browser.
To implement MVC in Spring, we will use a template engine. In the following section, we will talk about template engines and look at a few common ones used in Spring.
Template engines
To help with implementing MVC, we will need a template engine. A template engine allows us to write static template files in our application. When the application is running, a template engine replaces the variables in the static template files with values, creating a dynamic webpage that is sent to a client. This way, our code is more consistent and organized, and the view rendering code is better separated from the logic responsible for building it. We will discuss three template engines commonly used in Spring.
1) JSP is the default method for implementing MVC in Spring, and it comes with the default installation of Spring. With the help of JSP, we can write HTML pages with variables that allow us to build dynamic pages with the data from our model. When JSP finds a variable in a template page, it will resolve it through the controller using the ModelMap object. The ModelMap object will map the variable name to a value, replacing the variable name on the template page. This allows us to create a dynamic page where variable data can be loaded as required.
2) Thymeleaf allows the processing of HTML, XML, text, Javascript, and CSS files. It also allows for more complex templating, such as conditional evaluation within the HTML template, giving more power than the default JSP pages.
3) Freemarker is built by Apache and can generate web pages, source code, XML, configuration files, emails, and other text-based formats. Freemarker isn't bound to servlets or web-related content, allowing it to be used for non-web applications as well.
Any of these template engines can be used to implement the MVC architecture in Spring. If an application is simple, JSP is usually sufficient. If you want more control and complexity in your views, it would be ideal to use Thymeleaf. If your application is not web-based, or you would like the option to use MVC with offline components, Freemarker is a good choice.
Basic MVC example
We can create a simple MVC application using a Controller, which takes in a REST request such as GET. To start, we will declare a simple Controller using the @Controller annotation. In our Controller, we will implement a single @GetMapping method, which has a path and produces a TEXT_HTML_VALUE. When the get request is sent, the value returned will be a simple HTML page.
Java
@Controller
public class GreetController {
@GetMapping(value="/greet", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String greetUser() {
return "<html><p>Hello and welcome!</p></html>";
}
}Kotlin
@Controller
class GreetController {
@GetMapping(value = ["/greet"], produces = [MediaType.TEXT_HTML_VALUE])
@ResponseBody
fun greetUser(): String {
return "<html><p>Hello and welcome!</p></html>"
}
}The @Controller annotation will tell our DispatcherServlet that the class handles HTTP requests. Our HTML response acts like the view, which can be rendered in the browser when the @GetMapping path is accessed. Once the application is built and run, you can navigate to the /greet path to get the result below. The annotation @ResponseBody indicates that the greetUser method return value should be bound to a web response body and converted to an HTTP response body based on the TEXT_HTML_VALUE content type.
If we type this address in the browser, the result will be the following:
Conclusion
The MVC architecture can be used in Spring to create flexible and loosely coupled applications. When we create MVC applications, they will include a model, a view, and a controller, each handling a separate part of the application. With this setup, the DispatcherServlet can handle client requests and responses. Finally, we can use a template engine like JSP, Thymeleaf, and Freemarker to implement MVC in our applications.