Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Spring Web MVC Framework


May 14, 2021 Spring


Table of contents


MVC framework tutorial

The Spring web MVC framework provides a model-view-controlled architecture and components that can be used to develop flexible, loosely coupled web applications. The MVC pattern leads to the separation of different aspects of the application (input logic, business logic, and UI logic), while providing loose coupling between these elements.

  • The model encapsulates application data, and they usually consist of POJO.

  • Views are primarily used to render model data, and typically it generates HTML output that the client's browser can interpret.

  • Controllers are primarily used to process user requests and build appropriate models and pass them to view rendering.

DispatcherServlet

The Spring Web Model-View-Control (MVC) framework is designed around DispatcherServlet, which handles all HTTP requests and responses. Spring Web MVC DispatcherServlet's request processing workflow is shown in the following image:

Spring Web MVC Framework

Here is a sequence of events corresponding to dispatcherservlet incoming HTTP requests:

  • After receiving an HTTP request, DispatcherServlet selects and calls the appropriate controller based on HandlerMapping.

  • The controller accepts the request and calls the appropriate service method based on the GET or POST method used. The Service method sets up model data based on defined business logic and returns the view name to dispatcherservlet.

  • DispatcherServlet gets help from ViewResolver to define a view for request access.

  • Once the view is determined, DispatcherServlet passes the model data to the view and ends up in the browser.

All of the components mentioned above, namely HandlerMapping, Controller, and ViewResolver, are part of The Web ApplicationContext, an extension of ApplicationContext with some additional features necessary for web applications.

The configuration of the requirements

You need to map the requests you want DispatcherServlet to process by using .xml URL map in the web server file. Here is an example of explicitly declaring and mapping HelloWeb DispatcherServlet:


Web .xml files will be kept in the WebContent/WEB-INF directory of your application. W ell, when you initialize HelloWeb DispatcherServlet, the framework will attempt to load Chinese pieces of application content in the WebContent/WEB-INF directory located in the application [servlet-name]-servlet.xml In this case, our file will be HelloWeb-servlet .xml.

Next, servlet-mapping indicates which URLs will be processed by DispatcherServlet. All HTTP requests .jsp here will be handled by HelloWeb DispatcherServle t.

If you don't want to use the default file [servlet-name]-servlet.xml the default location WebContent/WEB-INF, you can customize the name and location of the file by adding the servlet listener ContextLoaderListener to the web.xml file, as follows:

<web-app...>

....
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
   <listener-class>
      org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>
</web-app>

Now, check the request configuration for helloWeb-servlet .xml file, which is located in the WebContent/WEB-INF directory of the web application:


<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

Here are some key points about HelloWeb-.xml files:

  • [servlet-name]-servlet.xml will be used to create a bean definition that redefines any defined bean with the same name globally.

  • <context:component-scan> activate the Spring MVC comment scanning feature, which allows the use of comments such as @Controller and @RequestMapping.

  • InternalResourceViewResolver uses defined rules to resolve view names. In accordance with the rules defined above, a logical view named hello is sent to the view implemented in the /WEB-INF/jsp/hello.jsp .jsp the file.

The next section shows you how to create actual components, such as controllers, patterns, and views.

Define the controller

DispatcherServlet sends a request to the controller to perform a specific function. note indicates that a particular class is the role of a controller. @RequestMapping comments are used to map URLs to the entire class or to a specific process.


@Controller
@RequestMapping("/hello")
public class HelloController{
   @RequestMapping(method = RequestMethod.GET)
   public String printHello(ModelMap model) {
      model.addAttribute("message", "Hello Spring MVC Framework!");
      return "hello";
   }
}

@Controller the class as a Spring MVC controller with comments. H ere, the first use of @RequestMapping indicates that all methods processed in the controller are relative to the /hello path. T he next comment @RequestMapping (method s RequestMethod.GET) is used to declare the printHello() method as the controller's default service method to handle HTTP GET requests. You can define other methods to handle any POST request in the same URL.

You can write the controller above in another form, and you can add additional properties @RequestMapping the following:


@Controller
public class HelloController{
   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String printHello(ModelMap model) {
      model.addAttribute("message", "Hello Spring MVC Framework!");
      return "hello";
   }
}

The value property indicates which processing method the URL maps to, and the method property defines the service method to handle HTTP GET requests. Here are a few key points to note about the controllers defined above:

  • You'll define the business logic you need in a service method. You can call other methods in this method on a per-demand basis.

  • Based on the defined business logic, you will create a model in this method. Y ou can set different model properties that will be accessed by the view and display the final result. This example creates a model with the property "message".

  • A defined service method can return a string containing the view name to render the model. This example returns "hello" as the name of the logical view.

Create a JSP view

Spring MVC supports many types of views for different representing techniques. T hese include JSPs, HTML, PDFs, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS profiles, JasperReports, and more. B ut we most often use JSP templates written with JSTL. So let's write a simple hello view in /WEB-INF/hello/hello.jsp in the article:

<html>
   <head>
   <title>Hello Spring MVC</title>
   </head>
   <body>
   <h2>${message}</h2>
   </body>
</html>

Among them, ${message is a property that we set inside the controller. You can have more than one property display in your view.

Spring Web MVC framework example

Based on these concepts, let's look at some important examples to help you build a Spring Web application:

Serial number Examples and descriptions
1 Spring MVC Hello World Example

This example will explain how to write a simple Spring Web Hello World application.

2 Spring MVC Form Handling Example

This example explains how to write a Spring Web application that uses HTML forms to submit data to the controller and display the results of processing.

3 Spring Page Redirection Example

Learn how to use page redirection in the Spring MVC framework.

4 Spring Static Pages Example

Learn how to access static and dynamic pages in the Spring MVC framework.

5 Spring Exception Handling Example

Learn how to handle exceptions in the Spring MVC framework.