What is needed for Spring MVC to work?
sobes.tech AI
Answer from AI
-
Dependencies: Add Spring Boot Web Starter (for Spring Boot) or spring-webmvc (for "classic" Spring MVC) to the project.
-
Configuration: Configure the DispatcherServlet:
- In Spring Boot: It is auto-configured when Spring Boot Web Starter is present.
- In "classic" Spring MVC:
- Register DispatcherServlet in
web.xmlor use annotations (AbstractAnnotationConfigDispatcherServletInitializer). - Specify a configuration class or XML file for the Spring context (
WebApplicationContext).
- Register DispatcherServlet in
-
Controllers: Create classes annotated with
@Controlleror@RestControllerto handle HTTP requests. Methods in these classes should be annotated for request mapping (e.g.,@GetMapping,@PostMapping, etc.). -
View Resolver (optional): Configure a View Resolver if using view templates (JSP, Thymeleaf, FreeMarker, etc.) so Spring can locate and render the appropriate views. Spring Boot auto-configures the View Resolver based on the presence of template libraries.
-
Servlet container deployment: Deploy the application in a servlet container (e.g., Tomcat, Jetty), or use the embedded one in Spring Boot.