Creating a Web App
To actually execute the MVC design pattern practically, you construct a Java class and decorate it with the extremely powerful @Controller annotation.
1. Defining the Controller
The @Controller annotation registers the class specifically within the Spring IoC Container and signals the DispatcherServlet that this class contains web endpoints.
The @GetMapping annotation strictly maps an explicit URL path to a specific method automatically securely.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GreetingController {
// Captures requests terminating at EXACTLY "http://localhost:8080/greet"
@GetMapping("/greet")
public String displayGreeting(
@RequestParam(name="name", required=false, defaultValue="World") String name,
Model model) {
// Adding data payload natively to the Model structure
model.addAttribute("username", name);
// Returns the explicit View name perfectly identifying the destination HTML template
return "greeting-view";
}
}
2. Using RequestParams
In the example automatically above, the explicit @RequestParam annotation grabs query variables mapped directly from the URL.
If a user naturally navigates identically to /greet?name=Alice, Spring actively binds the parameter Alice implicitly into the method signature String name variable accurately.
3. The View Template
When the Controller explicitly returns the string "greeting-view", Spring utilizes the internal ViewResolver carefully mapping it predictably to an HTML directory location natively (typically rendering src/main/resources/templates/greeting-view.html).
The HTML engine specifically parses the Model property username securely cleanly into the page.