Computer scienceBackendSpring BootWeb

Introduction to Spring Web MVC

11 minutes read

Spring Web MVC, commonly known as Spring MVC, is one of the modules of the core Spring framework. Spring MVC is used to create websites and RESTful services. It provides ready components that simplify and speed up the development process.

As the name suggests, the Spring MVC framework follows the MVC (Model-View-Controller) pattern, which helps organize code by separating the different parts of an application: input, UI, and business logic.

Applications commonly created with Spring MVC can be characterized by the type of data they return:

  • HTML: The application creates web pages that can be viewed via a web browser (client). This type of app fully uses the underlying MVC pattern. The model stores the application data. The view is responsible for rendering model data and generating HTML output. The controller processes user requests, builds an appropriate model, and passes it to the view for rendering.

  • JSON/XML: The application provides RESTful services that generate JSON or XML data. Various clients, including other services, can use these data. The structure of this type of program is similar to the first type, although Spring MVC no longer creates a view. Instead, JSON/XML data is returned, and another program (client) is responsible for rendering and visualizing the returned model data.

In addition to the above, Spring MVC can handle other data types and formats.

In this topic, you'll learn about the Spring Web MVC framework, and we'll create a very simple web application that returns a welcome page. We'll start with the basics and leave Spring Boot's implementation of the MVC pattern for later. You'll learn that and other interesting features of this framework in the upcoming topics.

Dependency

To develop and run a Spring MVC web application in Spring Boot, we must include the following dependency in our Spring Boot project.

For Gradle-based Spring Boot projects:

dependencies {
   // ...
   implementation 'org.springframework.boot:spring-boot-starter-web'
   // ...
}

For Maven-based Spring Boot projects:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

This starter dependency combines dependencies required to start writing web apps. It also provides auto-configuration, which means that after we've added the dependency, we can begin writing the application code. We can also override the default configuration if we need to.

One of the included dependencies is an embedded server.

Web server

As you probably know, the difference between a web application and a usual app is that a web app requires a web server — a special program to run it.

A server is embedded when it is part of an application, and we don't need to install it separately. This is convenient because it allows us to package the whole application in one executable .jar file that we can move and run like a regular application.

We can also package an application in a .war file that doesn't contain a web server. Such an app should be deployed on an external server. In our projects, we'll only use the .jar format.

The default embedded server is Apache Tomcat, which is free, open-source, lightweight, and one of the most popular servers. It remains actively developed and kept up to date.

Now that we know how to add Spring MVC to a project and what an embedded server is, let's create and run a web app.

Don't forget that we can generate a basic Spring Boot project using the Spring Initializr or specific IDEs. This page describes how to generate such a project using IntelliJ IDEA.

Log

Let's assume we started a new Spring Boot project and added the web dependency without any code. If we run such an app, it will start the built-in Tomcat server, and we'll see some new log messages related to Spring MVC in the console:

Tomcat's log messagesLet's examine some of the log entries. The first line related to Spring MVC contains the following information:

... Tomcat initialized with port(s): 8080 (http)

This line shows that the embedded Tomcat server started on port 8080. This is the default port provided by auto-configuration. Unless otherwise specified, we will use this port in the upcoming steps and topics. The above line is followed by additional initialization information, and we see a line that contains the Apache Tomcat version:

... Starting Servlet engine: [Apache Tomcat/9.0.45]

In our case, the version is 9.0.45. This information is useful in some cases. After the version information, more log entries follow, and the last line related to Spring MVC contains the following information:

... Tomcat started on port(s): 8080 (http) with context path ''

This line indicates that the initialization was completed successfully, and the Tomcat server is running. It also shows the default context path.

The context path is the prefix of the URL path at which we can access our application. It is also known as the sub-path or sub-directory. As we can see, the default context path is empty. This means the web app can be accessed at http://localhost:8080/. Apps are often hosted somewhere other than the default context path. For example, the context path blog means the app can be accessed via a URL of the form http://localhost:8080/blog. A context path can also be nested, such as blog/v1.

You'll learn how to change the default port and context path in the upcoming sections — but first, let's complete our app.

Web page

To complete the app, we'll create a simple HTML file in the folder responsible for static content and then open it via a web browser. The location of this folder is src/main/resources/static.

Note that if there is no static folder in the resources folder, we must create it manually.

We can place any static content (images, stylesheets, JavaScript, and so forth) that we want to serve to the browser in the static folder. If we create an HTML file with the name index.html in this folder, this file will be available at the root URL.

Let's create an index.html file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Main</title>
</head>
<body>
    <h1>Welcome!</h1>
</body>
</html>

Now, if we rerun the application and navigate to http://localhost:8080/ in our web browser, we'll see the following web page:

html page with "Welcome!" text in browser

We can also access the file by its name: http://localhost:8080/index.html.

We can create other HTML files and access them by name, as in the example above. Feel free to experiment with this feature. To create a more complex-looking page, you can include CSS and JavaScript.

The above approach can be used to create simple web apps that return hardcoded pages. More complex programs require us to add some code. For example, we may need to include data from a database on a web page. To do so, we need to write code that fetches data from a database and adds it to a page.

As mentioned earlier, we can change the default port and context path. Let's learn how to do that now.

Configuration

Usually, it's a good idea to prefer auto-configuration, but there are cases where we want to have a custom context path or port. We may also want to change other app properties. We can do so using the application.properties file.

We can change the port by including the following line in application.properties.

server.port=9090

While running a project, you may encounter a situation where your program can't start, and the console logs show the port is already in use. This means that another program uses the port on which you are trying to run your app. Changing the port should solve the problem.

Here is how you can change the context path in Spring Boot:

server.servlet.context-path=/myapp

If we change the port and context path and rerun the application, we'll see that the console log includes these changes:

... Tomcat started on port(s): 9090 (http) with context path '/myapp'

From now on, our web app can be accessed at http://localhost:9090/myapp.

Conclusion

Here's what we've learned on this topic:

  • Spring MVC is a framework used to create web apps. You can add it to a project using the spring-boot-starter-web dependency.

  • An embedded server is the component of a web app required to run it. The default server for Spring MVC is Apache Tomcat.

  • The default port is 8080, and the context path is empty.

  • You can change the default port and context path using the application.properties file.

  • If we place an index.html file in the src/main/resources/static folder, it will be available at the root URL.

  • We can place multiple HTML files in the src/main/resources/static folder and access them by name.

In the upcoming topics, you'll learn more about Spring Web MVC, but before you continue learning new features of this framework, let's practice what we've just learned by solving some tasks!

276 learners liked this piece of theory. 18 didn't like it. What about you?
Report a typo