Spring MVC Minimal Project: A Beginner’s Guide
Introduction
Spring MVC is a powerful framework for creating scalable and robust web applications. This guide will take you through
setting up a minimal Spring MVC project and understanding its structure, components, and functionality.
Key Takeaways:
- Learn to configure and build a Spring MVC project.
- Understand the roles of controller classes, view templates, and XML configurations.
- Gain hands-on experience running the application.
Setting Up a Spring MVC Project
Overview of Spring MVC
Spring MVC is based on the Model-View-Controller (MVC) design pattern, ensuring separation of concerns for better maintainability.
Tools and Dependencies
To build this project, use:
- IDE: Eclipse or IntelliJ IDEA
- Build Tool: Maven
- Server: Apache Tomcat
- Dependencies: Spring Framework libraries
Exploring the Components
Maven Configuration
The pom.xml file specifies the dependencies:
1 2 3 4 5 6 7 8 |
org.springframework spring-webmvc 5.3.10 javax.servlet javax.servlet-api provided |
Controller Logic
The MainController.java file handles incoming requests:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.studyeasy; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @RequestMapping("/") public String home() { return "home"; } } |
Explanation:
- The @Controller annotation marks this class as a controller.
- The @RequestMapping(“/”) maps the root URL to the home method.
- The method returns the view name (home.jsp).
View Templates
The home.jsp file renders the response:
1 2 3 4 |
<title>Welcome</title> <h1>Welcome to Spring MVC!</h1> |
Spring XML Configuration
The SpringSample-servlet.xml file connects the controller to the view:
1 |
Deployment Descriptor
The web.xml file configures the servlet:
1 2 3 4 5 6 |
SpringSample org.springframework.web.servlet.DispatcherServlet SpringSample / |
Running the Application
- Build the Project: Use Maven to install dependencies and compile the code.
- Deploy on Tomcat: Copy the WAR file to the webapps directory.
- Access the Application: Navigate to http://localhost:8080.
Output:
1 |
Welcome to Spring MVC! |
Conclusion
This guide introduced you to the foundational elements of Spring MVC, from setting up the project to running it
successfully. Understanding these basics will help you appreciate how Spring Boot builds upon the MVC framework to simplify development.