The Model-View-Controller (MVC) architecture can be used to create flexible and loosely coupled web applications. This architecture has three separate 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

So let’s talk about the components of the MVC architecture. Each of them handles a specific task, as follows:

  • The Model holds application data, generally using Java objects.
  • The View handles rendering model data, generating an output that 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 special component known as DispatcherServlet. The diagram below outlines the whole process completed by 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. HandlerMapping is implemented in the web.xml file and provides the mapping from URL patterns to their required controllers. Once the HandlerMapping is completed, the Controller will take over and 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 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 the ModelMap object. With this object, you can use the addAttribute method in order to map variable names in the view to the values in the model.

Once the Controller is completed, DispatcherServletwill utilize the component called ViewResolver to get the required view, based on 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 special type of engine known as a template engine. In the following section, we will talk about template engines and take a look at a few common ones that are 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. There are three common template engines used in Spring that we will discuss.

1) JSP is the default method of implementing MVC for Spring, and it comes with the default installation of Spring. With the help of JSP, we can write normal 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, which will replace 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 us 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, as well as source code, XML, configuration files, emails, and many other text-based formats. Freemarker isn’t bound to servlets or web-related content, which allows 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 to have more control and complexity in your views, it would normally be ideal to use Thymeleaf. If your application is not web-based, or you would like the option of using 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, which has a path and produces a TEXT_HTML_VALUE as a result. When this request is sent, the value returned will be a simple HTML page.

@Controller
public class GreetController {

    @GetMapping(value="/greet", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String greetUser() {
        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 @ReponseBody indicated that the greetUser method return value should be bound to the web response body and converted to HTTP response body based on the TEXT_HTML_VALUE content type.

If we type this address in the browser URL, the result will be the following:

Conclusion

MVC architecture can be used in Spring to create applications that are flexible and loosely coupled. When we create MVC applications, they will include a model, a view, and a controller, which each handle a separate part of the application. With this model, it is possible to use the DispatcherServlet to handle requests and responses for clients. Finally, we can use a template engine like JSP, Thymeleaf, and Freemarker to implement MVC in our applications.

Leave a Reply

Your email address will not be published.