In Spring Boot MVC, creating controllers and views is streamlined compared to traditional Spring MVC, thanks to embedded configurations and auto-configuration features. Here's a step-by-step guide to creating controllers and views in a Spring Boot MVC application.
1. Setting Up a Spring Boot Project
You can create a Spring Boot project via the Spring Initializr or using your preferred IDE (like IntelliJ IDEA or Eclipse).
Dependencies to Include:
- Spring Web: For building web applications.
- Thymeleaf (or JSP): For rendering views (templates).
Sample pom.xml
Configuration:
2. Creating a Controller
Create a controller class to handle incoming requests.
Example HomeController
Explanation:
@Controller
: Indicates that this class is a Spring MVC controller.@GetMapping("/welcome")
: Maps HTTP GET requests to the/welcome
URL.Model
: Used to pass data to the view.return "welcome"
: Refers to a template namedwelcome.html
(Thymeleaf) orwelcome.jsp
.
3. Creating a View
Create a view template to display the data returned by the controller.
Thymeleaf View (welcome.html
)
Place the HTML file in the resources/templates
directory.
Explanation:
th:text="${message}"
: Displays the value of themessage
attribute passed from the controller.
4. Running the Application
Main Application Class
Spring Boot automatically configures the embedded Tomcat server. Here's a basic application class:
5. Project Structure
Your project structure should look like this:
6. Accessing the Controller
Run your application and open your browser to:
You should see the message: "Welcome to Spring Boot MVC!"
Using JSP Instead of Thymeleaf
If you prefer JSP instead of Thymeleaf:
Add Dependencies in
pom.xml
:Configure
application.properties
:Create JSP File:
- Place
welcome.jsp
insrc/main/webapp/WEB-INF/views/
.
- Place
Summary
- Controllers handle requests using
@GetMapping
and other annotations. - Views (Thymeleaf or JSP) render the model data.
- Spring Boot's embedded Tomcat makes deployment seamless.
This setup provides a clear, MVC-structured approach to building web applications in Spring Boot.
Comments
Post a Comment