Stage 2: let a controller handle a request
Learning path / Stage 2 of 37
mvn spring-boot:run. Use the port specified for this stage and stop with Ctrl+C.Keep the same HTML files and add one Java class. Visiting /aboutus now runs our Java method before serving the page. DispatcherServlet is already part of our web setup from Stage 1; this stage adds our own controller method for it to dispatch to.
Download spring-controller.zip
GET /aboutus -> aboutUs() -> forward:/aboutus.html -> same HTML page@Controller lets Spring discover this class as a web controller. @GetMapping connects GET /aboutus to aboutUs(). The println message appears in the server terminal, not in the browser. forward:/aboutus.html is an internal handoff to the static file; the browser address stays /aboutus. No template engine is needed. /aboutus.html remains directly accessible and bypasses this method.
Try and verify: Open /aboutus and watch the server terminal. Then open /aboutus.html directly and observe that our message is not printed for that direct file request.
Open the files to study in this stage
package com.edupoly.hello;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/aboutus")
public String aboutUs() {
System.out.println("Someone requested the About Us page");
return "forward:/aboutus.html";
}
}
The ZIP contains every setup file and a README.html with instructions. You can run the supplied project directly.
After Stage 2: the Spring words to recognize
Focus: Connect the controller class we wrote to the object Spring manages.
| Term | Our concrete example | Its place in Spring |
|---|---|---|
| Controller | PageController.aboutUs() handles GET /aboutus through @GetMapping. | A Spring MVC controller handles a mapped web request. |
| Component | @Controller marks PageController as a specialized component. | Spring can discover eligible annotated classes in scanned packages. |
| Bean | Spring manages an instance of PageController. | A bean is the actual object Spring manages; PageController is the class definition. |
| Container | Spring creates and manages the PageController instance. | The Spring container is the system that manages these bean objects. |
The PageController instance is the specific object being managed. The About Us HTML file is a resource, not a bean. Stage 8 demonstrates constructor injection with a separate ProductFileReader.
You should now be able to say: I wrote the PageController class. Spring manages a PageController object as a bean and calls its mapped method.
One small check: In this example, point to the class, explain what its object is, and say why that object is called a bean.
Concepts used in this stage
Use the right column for a quick reminder, or open a concept above for its full explanation.