Spring MVC – Basics
Spring MVC simplifies web application development by handling HTTP requests and responses efficiently. The key components of Spring MVC include:
- DispatcherServlet: Acts as the front controller, handling all incoming requests.
- Controller: Processes requests and returns responses.
- View Resolver: Determines which view to render.
- Model: Stores data to be displayed on the view.
- Handler Mapping: Maps requests to appropriate controllers.
Spring MVC – Software Setup and Configuration (STS/Eclipse)
To start with Spring MVC, you need to set up your development environment. Follow these steps:
- Install JDK: Ensure you have Java Development Kit (JDK) installed.
- Install Eclipse/STS (Spring Tool Suite): STS is a specialized IDE for Spring applications.
- Set Up Spring Boot Project:
- Open STS/Eclipse.
- Go to File > New > Spring Starter Project.
- Select Spring Web dependency.
- Click Finish to generate the project.
Prerequisite (Spring Core Concepts)
Before diving into Spring MVC, you should understand the following Spring Core concepts:
- Spring Beans: Objects managed by the Spring container.
- Dependency Injection (DI): Injecting dependencies instead of creating them manually.
- Spring Boot Starter: Pre-configured dependencies for quick development.
- Spring Context: Manages the lifecycle of beans.
Core Spring MVC
A basic Spring MVC application includes:
- Controller Class
- View (JSP/HTML)
- Model (Java Class)
Example
Controller Class
@Controller
public class HomeController {
@RequestMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring MVC");
return "home"; // View name
}
}
View (home.jsp)
<html>
<body>
<h1>${message}</h1>
</body>
</html>
Spring MVC – Annotation
Spring MVC uses annotations to simplify configuration. Some important annotations include:
- @Controller: Defines a controller class.
- @RequestMapping: Maps HTTP requests to handler methods.
- @GetMapping / @PostMapping: Handle specific request types.
- @ModelAttribute: Binds method parameters to model attributes.
- @ResponseBody: Sends data as JSON or plain text.
Example
@Controller
public class GreetingController {
@GetMapping("/greet")
@ResponseBody
public String greet() {
return "Hello, Welcome to Spring MVC!";
}
}
Spring MVC – Form Handling
Spring MVC makes form handling easy using the @ModelAttribute annotation.
Example
Model Class
public class User {
private String name;
private String email;
// Getters and Setters
}
Controller
@Controller
public class UserController {
@GetMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String submitForm(@ModelAttribute("user") User user) {
return "success";
}
}
View (register.jsp)
<form action="register" method="post">
Name: <input type="text" name="name"/><br/>
Email: <input type="email" name="email"/><br/>
<input type="submit" value="Submit"/>
</form>
Spring MVC with JSTL
JSTL (JavaServer Pages Standard Tag Library) enhances JSP pages with dynamic capabilities.
Example
<c:forEach var="item" items="${list}">
<p>${item}</p>
</c:forEach>
Spring MVC with REST API
Spring MVC allows building REST APIs using @RestController.
Example
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello, API!";
}
}
Spring MVC with Database
Spring MVC can connect to databases using Spring Data JPA.
Example
Entity Class
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
private String name;
private String department;
// Getters and Setters
}
Repository
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
Controller
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository repo;
@GetMapping
public List<Employee> getEmployees() {
return repo.findAll();
}
}
Advantages of Spring MVC Framework
- Separation of Concerns: Clear division between Model, View, and Controller.
- Ease of Testing: Independent components make unit testing easier.
- Annotation-Based Configuration: Reduces XML configuration.
- Integration with Other Technologies: Works well with Hibernate, REST, and JSP.
- Scalability: Ideal for building large applications.
Frequently Asked Questions
What is the difference between Spring Boot MVC and Spring Boot?
Spring MVC is a framework for building web applications, while Spring Boot simplifies setup with pre-configured components.
How does Spring MVC handle form submissions?
Spring MVC uses @ModelAttribute to bind form data to model objects.
Can Spring MVC be used for REST APIs?
Yes, by using @RestController instead of @Controller, you can build RESTful web services.
Conclusion
In this article, we learned the Spring Boot MVC framework, its architecture, and how it simplifies web application development. Spring Boot MVC follows the Model-View-Controller (MVC) pattern, making it easy to build scalable and maintainable applications. With features like auto-configuration and embedded servers, it speeds up development. Understanding its concepts helps in creating efficient and well-structured web applications.