The Spring Framework’s MVC framework module provides support for building web applications using the Model-View-Controller (MVC) architectural pattern. The MVC pattern separates an application into three components:
- Model: Represents the data and business logic of the application.
- View: Renders the data from the model as a web page or other type of output.
- Controller: Handles user input and manages the communication between the model and the view.
The Spring MVC framework provides classes and annotations that make it easy to build these components and wire them together. Here’s a simple example of how you might use the Spring MVC framework to build a web application:
@Controller
public class MyController {
@GetMapping("/hello")
public ModelAndView hello() {
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", "Hello, world!");
return modelAndView;
}
}
@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class AppConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
In this example, we have a MyController
class that uses Spring’s @Controller
annotation to indicate that it handles HTTP requests. We also have a hello()
method that handles GET requests to the /hello
endpoint and returns a ModelAndView
object. The ModelAndView
object contains the name of the view (hello
) and a message that will be rendered by the view.
We also have an AppConfig
class that configures the Spring MVC framework. It uses Spring’s @EnableWebMvc
annotation to enable the MVC framework and Spring’s @ComponentScan
annotation to scan for components in the com.example
package. It also defines a ViewResolver
bean that tells the framework where to find the view templates.
Finally, we have a JSP view template located at /WEB-INF/views/hello.jsp
that renders the message passed to it by the controller:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
This JSP template uses the ${message}
expression language syntax to render the message passed to it by the controller.
Overall, the Spring MVC framework provides a powerful and flexible way to build web applications using the MVC pattern, allowing developers to easily build and wire together the components of their application.