Spring MVC is a component of the Spring Framework, one of the most popular Java frameworks for building web applications. It follows the Model-View-Controller (MVC) design pattern, which separates the application logic into three interconnected components: Model, View, and Controller. This separation helps to manage application complexity, facilitates unit testing, and promotes a clean separation of concerns.
The architecture of Spring MVC is based on the traditional MVC pattern, which consists of the following components:
@Controller
in Spring MVC.At the core of Spring MVC is the DispatcherServlet
. It acts as the front controller, receiving all incoming requests and dispatching them to the appropriate controllers based on the URL mapping. This central routing mechanism simplifies the handling of requests and improves maintainability.
Spring MVC uses annotations to handle request mapping. The @RequestMapping
annotation (or more specific ones like @GetMapping
, @PostMapping
) allows you to define the URL patterns to which a controller method responds.
ModelAndView is a central component in Spring MVC that allows you to send data to the view along with the view name. It encapsulates both the model and the view together and is often used in controller methods to render the final output.
Spring MVC provides support for form handling through data binding. You can bind form parameters to Java objects, making it easy to retrieve user input and perform validation.
Spring MVC has built-in support for exception handling. You can create global exception handlers with the @ControllerAdvice
annotation to handle errors and send appropriate responses back to the client.
To illustrate how Spring MVC works, let’s create a simple CRUD application for managing a list of books.
First, create a Maven project and add the necessary dependencies for Spring MVC in your pom.xml
:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.10</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.10</version> </dependency> <!-- Add any other necessary dependencies --> </dependencies>
Create a web.xml
file in the src/main/webapp/WEB-INF
directory to configure the DispatcherServlet
:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Create a dispatcher-servlet.xml
file in the src/main/webapp/WEB-INF
directory to define the beans:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <context:component-scan base-package="com.example.controller"/> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
Create a simple Book
model:
package com.example.model; public class Book { private Long id; private String title; private String author; // Getters and Setters }
Now, develop a BookController
to handle HTTP requests related to books:
package com.example.controller; import com.example.model.Book; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/books") public class BookController { private List<Book> books = new ArrayList<>(); @GetMapping public String listBooks(Model model) { model.addAttribute("books", books); return "book-list"; } @GetMapping("/add") public String showAddBookForm(Model model) { model.addAttribute("book", new Book()); return "add-book"; } @PostMapping public String addBook(@ModelAttribute Book book) { books.add(book); return "redirect:/books"; } }
Create JSP files in src/main/webapp/WEB-INF/views
for listing and adding books.
book-list.jsp:
<html> <head> <title>Book List</title> </head> <body> <h2>Book List</h2> <table> <tr> <th>Title</th> <th>Author</th> </tr> <c:forEach var="book" items="${books}"> <tr> <td>${book.title}</td> <td>${book.author}</td> </tr> </c:forEach> </table> <a href="${pageContext.request.contextPath}/books/add">Add a Book</a> </body> </html>
add-book.jsp:
<html> <head> <title>Add Book</title> </head> <body> <h2>Add Book</h2> <form action="${pageContext.request.contextPath}/books" method="post"> <label>Title:</label> <input type="text" name="title" required/> <label>Author:</label> <input type="text" name="author" required/> <input type="submit" value="Add Book"/> </form> <a href="${pageContext.request.contextPath}/books">Back to Book List</a> </body> </html>
With everything set up, you can now run your application using a servlet container like Apache Tomcat. When you navigate to /books
, you should see your book list, and clicking on "Add a Book" will lead you to the form for adding new books.
By following this guide, you have built a basic CRUD application utilizing the Spring MVC framework! Spring MVC's ease of use, combined with the power of the larger Spring ecosystem, makes it a go-to choice for building modern Java web applications.
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS
28/11/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS