1. Introduction to Spring MVC

Referring to MVC, students who have participated in Web application development are familiar with it. It is an architectural mode developed by the presentation layer (which can also be understood as the layer directly presented to users). M stands for Model, referring to data Model, V stands for View, referring to View pages, such as JSP and Thymeleaf. C stands for Controller, which is used to process requests made by users on the client (browser).

Spring MVC is based on the MVC pattern to help you build Web applications that are as flexible and loosely coupled as the Spring framework.

In other words, Spring MVC is spring-based and is primarily used to develop Web applications.

2. Spring MVC request flow

In Web applications, requests are essential. Each request is initiated by the user (client) and ends when the user (client) receives the response. The following diagram shows each flow of a request through Spring MVC:

Let’s take a look at each of these processes:

  1. The request leaves the browser (① in the figure) with information about what the user requested, such as the requested URL and submitted form information.
  2. It then goes to the first stop of the request, Spring’s DispatcherServlet, whose job is to send the request to the Spring MVC controller.
  3. Because there will be multiple controllers in the application, the DispatcherServlet queries one or more handler mapping, which determines which controller the request should be sent to based on the URL the request carries (② in the figure).
  4. Once the controller is identified, the DispatcherServlet sends the request to the identified controller and waits for the controller to process the information submitted by the user, although typically the controller does little of the work itself and delegates the business logic to one or more service objects (③ in the figure).
  5. After the controller completes the business logic processing, it usually generates some Model information, which needs to be returned to the user and displayed in the browser. In order to display this information in a friendly way, such as in Html, we need to send the information to a View, such as JSP, Thymeleaf.
  6. The last thing the controller does is wrap up the model data and label the view name for rendering output. It sends the request back to the DispatcherServlet with the model and view name (figure 4), but the controller only returns the logical name of a view, not a specific view. This logical name will be used to find the real view that produced the result. The DispatcherServlet uses the View Resolver to match the logical view name to a particular view (⑤ in the figure), such as JSP or Thymeleaf.
  7. The final stop of the request is the implementation of the view (⑥ in the figure), where the view renders output using model data, which is passed to the user/client via the response object (⑦ in the figure).

Now that you know the Spring MVC request flow, let’s look at how to set up and configure a Spring MVC project.

3. Build the Spring MVC project

We are still using the new Spring-Action project from the previous blog. If you are interested, you can check out the first 11 posts in this series or download the source code directly: github.com/zwwhnly/spr… .

3.1 Adding a Dependency

To use Spring MVC, we first need to add the following dependencies to pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.18. RELEASE</version>
</dependency>

<! -- Other Web dependencies -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
Copy the code

Since we will deploy the project to Tomcat later, we configure the package as war package in pom.xml:

<packaging>war</packaging>

<build>
    <plugins>
        <! -- Other configuration -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.3</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
Copy the code

3.2 Creating a Demo page

Create a new views directory under SRC /main/resources, and create an index.jsp page under this directory as follows:

<%@ page contentType="text/html; charset=UTF-8" language="java" pageEncoding="UTF-8" %> <html> <head> <title>Spring MVC</title> </head> <body> <pre> Welcome to Spring MVC world </pre> </body> </html>Copy the code

The possible problem here is that when you right-click to create a JSP file, there is no JSP file template, as follows:

The solution is as follows:

Click File–Project Structure to open the Project Structure dialog, select Modules on the left, and then click the + sign to select Web

Now right-click on the new JSP file again and you will see the JSP file template:

At this point, a Web folder is generated in the project root directory, which can be deleted.

3.3 Spring MVC Configuration

Create a new configuration class MyMvcConfig as follows:

package chapter05.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/** * Spring MVC configuration */
@Configuration
@EnableWebMvc
@ComponentScan("chapter05")
public class MyMvcConfig {
    /** * View resolver configuration **@return* /
    @Bean
    public InternalResourceViewResolver viewResolver(a) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);

        returnviewResolver; }}Copy the code

Matters needing attention:

1) The configuration class uses the @enableWebMVC annotation to enable Spring MVC, which turns on some of the default configurations.

2) This configuration class configures the view parser, in this case the view parser for JSP.

View the parser, we set the prefixes and suffixes, if the controller is returned in the logical view name in the index, the actual rendering when the view is/WEB – INF/classes/views/index. The JSP, Why is set prefix/WEB – INF/classes/views/rather than/SRC/main/resources/views /, that’s because the project directory is compiled runtime/WEB – INF/classes/views /.

If no JSP files are in the directory after compilation, add the following configuration to pom.xml:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.jsp</include>
                <include>**/*.js</include>
            </includes>
        </resource>
    </resources>
</build>
Copy the code

3.4 Web configuration

Create a New WebInitializer for the Web configuration class.

package chapter05.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MyMvcConfig.class);
        context.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet("dispatcher".new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1); }}Copy the code

To focus attention here is that this class implements an interface WebApplicationInitializer pay equal attention to write the onStartup () method, which is Spring WebApplicationInitializer class provides used to configure the Servlet version 3.0 + configuration interface, This can replace web.xml.

3.5 Creating a Controller

Create a new controller HelloController as follows:

package chapter05.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/index")
    public String hello(a) {
        // The logical view name returned here
        return "index"; }}Copy the code

The @controller annotation in the above code declares that this is a Controller, @requestMapping (“/index”) is used to configure the URL mapping, now the question is, how do we see this code working?

This involves project packaging and project deployment, which we’ll move on to.

4. Deploy the project to Tomcat

4.1 Packaging (WAR Package)

Since our project is managed by Maven and packaged as a WAR package and plug-in are configured in POP.xml, we can find Maven Explorer on the right side of IDEA and click clean as shown below:

Then click package:

The resulting WAR package looks like this:

This is the WAR package we will deploy to Tomcat.

4.2 Tomcat Installation and Deployment

Now that you are deploying to Tomcat, there are two questions that need to be answered:

  1. What is Tomcat?
  2. How do I install Tomcat?

To answer the first question, Tomcat is a free open source lightweight Web application server, if you’ve ever been around. NET Web development, which is similar to IIS.

To answer the second question, follow the steps below to install Tomcat.

Tomcat 8.5.45 Released Tomcat 8.5.45 Released

Then choose the appropriate version to download, since my development machine is Windows 64-bit OS, I choose the version shown below:

E:\Tools\apache-tomcat-8.5.45-windows-x64\apache-tomcat-8.5.45 -x64\apache-tomcat-8.5.45

Webapps is the directory where the website will be deployed.

Once the installation is complete, the question is how do I start Tomcat?

The first method is to double-click tomcat8.exe in the bin directory:

Enter http://localhost:8080/ in the browser. If the following page is displayed, Tomcat is successfully installed and deployed.

The disadvantage of using this method is that if you close the tomcat8.exe window, Tomcat will also be closed, which is very inconvenient. Therefore, it is recommended to use the second method, install Tomcat as a background service, let it run in the background, as follows:

Open computer – Properties – Advanced System Settings – Advanced environment Variables, add system variables:

Variable name: CATALINA_HOME

Variable value: E:\Tools\apache-tomcat-8.5.45-windows-x64\apache-tomcat-8.5.45 (where you decompressed Tomcat)

Then edit the system variable Path and add the following at the end:

; %CATALINA_HOME%\lib; %CATALINA_HOME%\bin

Then open the CMD window as the administrator, switch to the bin directory of Tomcat, and run the service.bat install command.

Then open the Windows services list and you will see a Tomcat8 service:

Modify the service to start automatically and start it to run the Tomcat server in the background.

If you’re wondering why the new system variable must be CATALINA_HOME, use Notepad to open the bin directory in service.bat and see the following:

As you can also see from the figure above, running Tomcat relies on the environment variable JAVA_HOME (to configure the JAVA SDK path), but I’ve done this before, as shown below:

4.3 Deploying the WAR Package to Tomcat

Copy the spring-action-1.0-snapshot. war package to the Tomcat webapps directory:

Since our Tomcat server is set up to run in the background, after a while the directory will generate a spring-action-1.0-snapshot folder with the same name as the WAR package. The directory structure is as follows:

Our code and JSP view files are in the Classes folder in the WEB-INF directory:

Enter the address http://localhost:8080/spring-action-1.0-SNAPSHOT/index in your browser, the page display as shown below:

5. Source code and reference

Source code address: github.com/zwwhnly/spr… Welcome to download.

Craig Walls: Spring In Action (4th Edition)

Java EE Development Disruptor: Spring Boot Combat by Wang Yunfei

【IntelliJ IDEA】 Use IDEA to solve the problem of creating a JSP file and not finding the new option of JSP file template

Tomcat installation and configuration tutorial

Tomcat installation and background operation method