Building a Spring MVC Application with Maven
Now that you have set up your development environment, let's start building a Spring MVC application using Maven.
Configuring the Maven Project
- Open the
pom.xml
file in your IntelliJ IDEA project.
- Add the necessary dependencies for Spring MVC and Thymeleaf (the view template engine) by adding the following code inside the
<dependencies>
section:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
- Add the Spring Boot Maven plugin to the
<plugins>
section of the pom.xml
file:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.0</version>
</plugin>
</plugins>
</build>
Implementing the Spring MVC Controller
In the HelloController.java
file, you can define the controller logic that will handle the incoming requests and return the appropriate view:
package com.labex.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/")
public String hello(Model model) {
model.addAttribute("message", "Hello from LabEx Spring MVC!");
return "hello";
}
}
Configuring the Spring MVC Application
To configure the Spring MVC application, you'll need to create a SpringMvcApplication.java
file in the root package (e.g., com.labex.springmvc
) with the following content:
package com.labex.springmvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringMvcApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMvcApplication.class, args);
}
}
Running the Spring MVC Application
- In the IntelliJ IDEA terminal, navigate to your project directory and run the following command to build and start the application:
mvn spring-boot:run
- Once the application is running, open your web browser and navigate to
http://localhost:8080/
. You should see the "Hello from LabEx Spring MVC!" message displayed on the page.
Congratulations! You have successfully built a Spring MVC application using Maven in IntelliJ IDEA. You can now continue to enhance your application by adding more functionality, such as additional controllers, services, and views.