TP2.1 - "Greeting" Application with Spring Boot
Objectives
This practical work will allow you to:
- Create your first Spring Boot project with Spring Initializr
- Configure Visual Studio Code for Spring Boot development
- Create a simple REST controller
- Understand the structure of a Spring Boot project
- Solve common startup issues
Prerequisites
Before starting, make sure you have installed:
- JDK 17 or higher
- Visual Studio Code
- Required VS Code Extensions:
- Extension Pack for Java
- Spring Boot Extension Pack
- Maven for Java
- Maven 3.9+ (recommended for stability)
Checking Prerequisites
# Check Java
java -version
# Check Maven
mvn -version
Part 1: Creating the Project with Spring Initializr
Step 1.1: Access Spring Initializr
Open your browser and go to: https://start.spring.io/
Step 1.2: Project Configuration
Configure your project with the following settings:
| Parameter | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.2.0 (or latest stable version) |
| Group | com.example |
| Artifact | greeting |
| Name | greeting |
| Package name | com.example.demo |
| Packaging | Jar |
| Java | 17 |
Step 1.3: Adding Dependencies
Click on "Add Dependencies" and add:
- Spring Web - To create REST web applications
Important: For this practical work, we ONLY add Spring Web. Do not add:
- Spring Data JPA
- PostgreSQL Driver
- Lombok
(We will see these dependencies in the following practical works)
Step 1.4: Generating the Project
- Click on the Generate button
- A ZIP file will be downloaded:
greeting.zip - Unzip this file into your workspace (e.g.,
C:\workspace\greeting)
Part 2: Opening the Project in VS Code
Step 2.1: Open the Project
- Launch Visual Studio Code
- Menu: File → Open Folder
- Select the unzipped
greetingfolder - VS Code will automatically detect the Maven project
Step 2.2: Wait for Initialization
VS Code will:
- Download Maven dependencies
- Configure the Java project
- Index the files
Note: The first time may take a few minutes.
Step 2.3: Project Structure
You should see the following structure:
greeting/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/demo/
│ │ │ └── GreetingApplication.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
├── pom.xml
└── README.md
Part 3: Creating the Classes
Step 3.1: Create the Greeting Class
- In VS Code, right-click on
src/main/java/com/example/demo - Select New File
- Name the file:
Greeting.java
Greeting class code:
package com.example.demo;
public class Greeting {
private Long id;
private String content;
public Greeting(Long id, String content) {
super();
this.id = id;
this.content = content;
}
public Long getId() {
return id;
}
public String getContent() {
return content;
}
public void setId(Long id) {
this.id = id;
}
public void setContent(String content) {
this.content = content;
}
}
Step 3.2: Create the GreetingController Class
- In the same folder, create a new file:
GreetingController.java
Controller code:
package com.example.demo;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value="name") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Part 4: Checking the pom.xml
Step 4.1: Open pom.xml
Open the pom.xml file and check the dependencies.
Expected dependencies (only 2):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Step 4.2: Explanation of Dependencies
| Dependency | Role |
|---|---|
spring-boot-starter-web | Provides everything needed to create REST web applications (Tomcat, Spring MVC, Jackson) |
spring-boot-starter-test | Provides testing tools (JUnit, Mockito, etc.) |
Step 4.3: If You Have Additional Dependencies
If you mistakenly added:
spring-boot-starter-data-jpapostgresqllombok
REMOVE THEM from the pom.xml to avoid errors.
Why? These dependencies require additional configuration (database, etc.) that we do not do in this practical work.
Part 5: Compilation and Execution
Step 5.1: Clean and Compile with Maven
Option A: Via VS Code Integrated Terminal
- Open the terminal: Terminal → New Terminal
- Run the commands:
mvn clean
mvn install
Option B: Via Maven Extension
- Open the Maven view (Maven icon in the sidebar)
- Expand your project
- Right-click on clean → Run
- Right-click on install → Run
Step 5.2: Run the Application
Option A: Via Terminal
mvn spring-boot:run
Option B: Via VS Code
- Open
GreetingApplication.java - Click on Run above the
mainmethod - Or press F5
Step 5.3: Check the Startup
You should see in the console:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::
...
Started GreetingApplication in X.XXX seconds
The server starts on port 8080 by default.
Part 6: Testing the Application
Step 6.1: Test in the Browser
Open your browser and test the following URLs:
Test 1:
http://localhost:8080/greeting?name=Armstrong
Expected result:
{
"id": 1,
"content": "Hello, Armstrong!"
}
Test 2:
http://localhost:8080/greeting?name=François
Expected result:
{
"id": 2,
"content": "Hello, François!"
}
Test 3:
http://localhost:8080/greeting?name=Patrick
Expected result:
{
"id": 3,
"content": "Hello, Patrick!"
}
Step 6.2: Observe the Counter
Refresh the page several times and observe:
- The ID increments with each call
- The counter is maintained in memory while the application runs
Step 6.3: Test with Postman (Optional)
If you have Postman installed:
- Create a new GET request
- URL:
http://localhost:8080/greeting?name=YourName - Click on Send
Part 7: Troubleshooting
Problem 1: Startup Error - Missing Dependencies
Symptom:
Failed to configure a DataSource: 'url' attribute is not specified
Cause: You probably have spring-boot-starter-data-jpa in your pom.xml
Solution:
Open pom.xml and remove these dependencies if present:
<!-- TO REMOVE -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Then restart:
mvn clean install
mvn spring-boot:run
Problem 2: Port 8080 Already in Use
Symptom:
Port 8080 was already in use.
Cause: Another application is already using port 8080.
Solution 1: Change Port
Open src/main/resources/application.properties and add:
server.port=8081
Or if you use application.yml:
server:
port: 8081
Then test with: http://localhost:8081/greeting?name=Test
Solution 2: Terminate the Process Using Port 8080
On Windows:
- Find the process:
netstat -ano | findstr :8080
-
Note the PID (Process ID) in the last column
-
Terminate the process (as administrator):
taskkill /F /PID <PID_number>
On macOS/Linux:
- Find the process:
lsof -i :8080
- Terminate the process:
kill -9 <PID>
Problem 3: Missing VS Code Extensions
Symptom: VS Code does not detect the Java project
Solution:
- Open the Extensions tab (Ctrl + Shift + X)
- Install these extensions:
- Extension Pack for Java (Microsoft)
- Spring Boot Extension Pack (VMware)
- Maven for Java (Microsoft)
- Restart VS Code
Problem 4: Maven Not Recognized
Symptom:
'mvn' is not recognized as an internal or external command
Solution:
- Download Maven: https://maven.apache.org/download.cgi
- Add Maven to your system PATH
- Restart the terminal
- Check:
mvn -version
Part 8: Comprehension Questions
Questions
-
What does the
@RestControllerannotation do? -
What is the difference between
@RestControllerand@Controller? -
What does
@GetMapping("/greeting")mean? -
Why use
AtomicLonginstead of a simpleLong? -
What does
@RequestParam(value="name")do? -
Why does the application automatically respond in JSON?
-
On which port does the application start by default?
-
What happens if you forget the
?name=parameter in the URL?
Expected Answers
(To be completed by the student)
Part 9: Additional Exercises
Exercise 1: Add an Optional Parameter
Modify the controller so that the name parameter is optional with a default value "World".
Hint: Use defaultValue in @RequestParam
Exercise 2: Add a New Method
Create a new method in the controller:
- URL:
/greeting/time - Returns: A greeting with the current time
Exercise 3: Modify the Template
Change the template to return "Bonjour, %s!" instead of "Hello, %s!"
Exercise 4: Add a Health Endpoint
Create an endpoint /health that simply returns "OK"
Deliverables
To submit (according to your teacher's instructions):
- Complete source code (ZIP project)
- Screenshots showing:
- The application running in VS Code
- Tests in the browser with different names
- The counter incrementing
- Reference: See screenshot examples
- Answer document to the comprehension questions
- Completed exercises (if requested)
Evaluation Criteria
| Criterion | Points |
|---|---|
| Project correctly created with Spring Initializr | 10% |
| Complete and functional Greeting and GreetingController classes | 30% |
| Application starts without error | 20% |
| Successful tests in the browser | 20% |
| Comprehension questions answered | 10% |
| Additional exercises (bonus) | 10% |
| Total | 100% |
Additional Resources
Documentation
Video Tutorials
Tools
- Postman - To test APIs
- JSON Formatter - To format JSON
Reference Screenshots
Documents with detailed screenshots:
Check the following Google Drive folder to see complete screenshots of each step of the practical work:
📸 Greeting Project Screenshots
Available content:
- PDF document with annotated screenshots
- Word document with visual instructions
- Examples of expected results
Note: These screenshots use STS (Spring Tool Suite), but the concepts and results are identical with VS Code.
Next Steps
Once this practical work is completed, you will be ready for:
- TP2: Connecting to a database with JPA
- TP3: Creating a complete CRUD API
- TP4: Securing with Spring Security
Important Notes
Best Practices:
- Always run
mvn cleanbeforemvn install - Stop the application (Ctrl + C) before restarting
- Check that the port is free before starting
- Regularly save your work
Help:
If you encounter problems:
- Check the "Troubleshooting" section
- Check the logs in the console
- Search for the error on Stack Overflow
- Contact your teacher
Good work and happy coding!