This project focuses on the core routing mechanism of Spring MVC: the @RequestMapping annotation. It demonstrates how to create a hierarchical URL structure by applying mappings at both the Class level and the Method level. This structure helps in organizing controllers based on specific modules (e.g., /boys/hello, /boys/springmvc).
Configured in web.xml, the DispatcherServlet acts as the single entry point. By mapping it to /, it intercepts every request and delegates it to the appropriate controller based on the @RequestMapping definitions.
This project illustrates a two-tier mapping strategy:
- Class-Level Mapping:
@RequestMapping("/boys")on theDemoControllerclass serves as a base path. All methods inside this class are relative to this path. - Method-Level Mapping:
@RequestMapping("/hello")inside the class defines the specific endpoint.
Resulting URL Logic:
Base Context Path + Class Mapping + Method Mapping
Example: http://localhost:8080/app/boys/hello
Since this project does not use a ViewResolver (like JSP), the @ResponseBody annotation is used. It tells Spring to bind the return value of the method directly to the HTTP response body, bypassing the usual view resolution logic.
- Spring Web MVC (6.1.13): The framework dependency for web support.
- Jakarta Servlet API (6.0.0): Required for compatibility with Tomcat 11.
Purpose: Defines the DispatcherServlet.
<servlet-name>:frontcontroller-dispatcher.- Matching Configuration: By convention, Spring looks for a file named
frontcontroller-dispatcher-servlet.xmlto load the application context.
Purpose: Spring configuration.
<context:component-scan>: Specifically looks intocom.student.controllersto find the@Controllerbean and register it in the Spring Container.
Purpose: Routing and Business Logic.
- Controller Logic:
- If you hit
/boys/hello, you get "Hello World". - If you hit
/boys/springmvc, you get the welcome message.
- If you hit
- Server Startup: Tomcat 11 loads the
web.xmland initializes theDispatcherServlet. - Context Loading: Spring scans the
com.student.controllerspackage. - Request Handling:
- User visits
/boys/hello. HandlerMappingidentifiesDemoControlleras the handler.HandlerAdapterexecutes thehelloWorld()method.
- User visits
- Response: The String is written directly to the browser because of
@ResponseBody.
- Java Version: Compatible with Java 17/21/25.
- Server: SmartTomcat 11 (Supports Jakarta EE 10/11).
- Packaging:
war(Web Application Archive).
- Endpoint 1:
http://localhost:8080/[context-path]/boys/hello- Output:
Hello World
- Output:
- Endpoint 2:
http://localhost:8080/[context-path]/boys/springmvc- Output:
Welcome to Spring mvc (Request Mapping Annotation)
- Output: