Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
Creating and running your first Spring MVC controller involves multiple steps including setting up the development environment, creating a Spring project, defining the MVC components, and testing the application.
Let's break this down step by step:
Download and Install Java: Ensure you have the Java Development Kit (JDK) installed. You can download it from the official Oracle website.
Install Eclipse with Spring Tool Suite (STS): Download Spring Tool Suite which is an Eclipse-based development environment that is customized for developing Spring applications.
File
-> New
-> Spring Starter Project
.Controller:
Create a new package named com.example.controller
. Inside this package, create a new class called HelloController
.
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HelloController { @RequestMapping("/hello") @ResponseBody public String helloWorld() { return "Hello, World!"; } }
Properties:
In src/main/resources
, you'll find an application.properties
file. Here you can specify properties. For now, just set the server port if you wish:
server.port=8081
Run the Application: Right-click on the main class (the one annotated with @SpringBootApplication
) -> Run As
-> Java Application
.
Access the Endpoint: Open a web browser and navigate to http://localhost:8081/hello
. You should see "Hello, World!" displayed.
Note: If you're creating a web application with Thymeleaf or JSP views, you'd also create a templates
or webapp
directory to hold your views. The controller would then return the name of the view rather than a direct string, and you wouldn't use @ResponseBody
. The above example uses @ResponseBody
to directly send a string response for simplicity.
That's it! You have created your first Spring MVC controller using Eclipse with Spring Tool Suite. Remember, this is a very basic introduction. Spring MVC offers many more features for building robust web applications.
Spring MVC Controller example in Spring Tool Suite:
@Controller
and define methods to handle different URL mappings. For example:@Controller public class HomeController { @RequestMapping("/home") public String home() { return "home"; } }