Junior
What is needed for Spring MVC to work?
sobes.tech AI
Answer from AI
To run Spring MVC, the following are necessary:
- Web server: A servlet container such as Apache Tomcat, Jetty, or Undertow for deploying the web application.
- Spring configuration:
- XML configuration or Java configuration (using annotations) defining Spring components (controllers, services, repositories, etc.) and their relationships.
- Configuration of
DispatcherServletin theweb.xmlfile or using Java configuration (AbstractAnnotationConfigDispatcherServletInitializer).DispatcherServletacts as the front controller of Spring MVC, delegating request processing to appropriate handlers.
- Maven/Gradle dependencies: Including necessary dependencies in the build file (
pom.xmlorbuild.gradle):spring-webmvc: The core dependency for Spring MVC.- Dependencies for views (Thymeleaf, JSP, FreeMarker, etc.) when using templating engines.
- Dependencies for validation (e.g., Hibernate Validator).
- Dependencies for JSON/XML processing (e.g., Jackson or JAXB).
- Controllers: Classes annotated with
@Controlleror@RestController, containing methods marked with@RequestMapping,@GetMapping,@PostMapping, etc., to handle incoming HTTP requests.
Example of minimal Java configuration:
// WebMvcConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebMvcConfig implements WebMvcConfigurer {
// Additional configuration if needed (e.g., ViewResolver setup)
}
Example of configuring DispatcherServlet using Java configuration:
// AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null; // No root contexts
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfig.class}; // Spring MVC configuration
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"}; // Map DispatcherServlet to root URL
}
}
Example of a simple controller:
// HelloController.java
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
model.addAttribute("name", name);
return "hello"; // View name (e.g., hello.jsp or hello.html)
}
}
In summary, Spring MVC is launched by deploying a web application (JAR or WAR) containing all necessary components and configuration on a web server. DispatcherServlet is initialized at startup and begins processing incoming web requests, directing them to the appropriate controllers based on mappings.