Sobes.tech
Middle

What is needed for Spring MVC to work?

sobes.tech AI

Answer from AI

  1. Dependencies: Add Spring Boot Web Starter (for Spring Boot) or spring-webmvc (for "classic" Spring MVC) to the project.

  2. 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.xml or use annotations (AbstractAnnotationConfigDispatcherServletInitializer).
      • Specify a configuration class or XML file for the Spring context (WebApplicationContext).
  3. Controllers: Create classes annotated with @Controller or @RestController to handle HTTP requests. Methods in these classes should be annotated for request mapping (e.g., @GetMapping, @PostMapping, etc.).

  4. 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.

  5. Servlet container deployment: Deploy the application in a servlet container (e.g., Tomcat, Jetty), or use the embedded one in Spring Boot.