Skip to main content

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:

ParameterValue
ProjectMaven
LanguageJava
Spring Boot3.2.0 (or latest stable version)
Groupcom.example
Artifactgreeting
Namegreeting
Package namecom.example.demo
PackagingJar
Java17

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​

  1. Click on the Generate button
  2. A ZIP file will be downloaded: greeting.zip
  3. 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​

  1. Launch Visual Studio Code
  2. Menu: File → Open Folder
  3. Select the unzipped greeting folder
  4. 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​

  1. In VS Code, right-click on src/main/java/com/example/demo
  2. Select New File
  3. 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​

  1. 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​

DependencyRole
spring-boot-starter-webProvides everything needed to create REST web applications (Tomcat, Spring MVC, Jackson)
spring-boot-starter-testProvides testing tools (JUnit, Mockito, etc.)

Step 4.3: If You Have Additional Dependencies​

If you mistakenly added:

  • spring-boot-starter-data-jpa
  • postgresql
  • lombok

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

  1. Open the terminal: Terminal → New Terminal
  2. Run the commands:
mvn clean
mvn install

Option B: Via Maven Extension

  1. Open the Maven view (Maven icon in the sidebar)
  2. Expand your project
  3. Right-click on clean → Run
  4. Right-click on install → Run

Step 5.2: Run the Application​

Option A: Via Terminal

mvn spring-boot:run

Option B: Via VS Code

  1. Open GreetingApplication.java
  2. Click on Run above the main method
  3. 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:

  1. Create a new GET request
  2. URL: http://localhost:8080/greeting?name=YourName
  3. 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:

  1. Find the process:
netstat -ano | findstr :8080
  1. Note the PID (Process ID) in the last column

  2. Terminate the process (as administrator):

taskkill /F /PID <PID_number>

On macOS/Linux:

  1. Find the process:
lsof -i :8080
  1. Terminate the process:
kill -9 <PID>

Problem 3: Missing VS Code Extensions​

Symptom: VS Code does not detect the Java project

Solution:

  1. Open the Extensions tab (Ctrl + Shift + X)
  2. Install these extensions:
    • Extension Pack for Java (Microsoft)
    • Spring Boot Extension Pack (VMware)
    • Maven for Java (Microsoft)
  3. Restart VS Code

Problem 4: Maven Not Recognized​

Symptom:

'mvn' is not recognized as an internal or external command

Solution:

  1. Download Maven: https://maven.apache.org/download.cgi
  2. Add Maven to your system PATH
  3. Restart the terminal
  4. Check: mvn -version

Part 8: Comprehension Questions​

Questions​

  1. What does the @RestController annotation do?

  2. What is the difference between @RestController and @Controller?

  3. What does @GetMapping("/greeting") mean?

  4. Why use AtomicLong instead of a simple Long?

  5. What does @RequestParam(value="name") do?

  6. Why does the application automatically respond in JSON?

  7. On which port does the application start by default?

  8. 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):

  1. Complete source code (ZIP project)
  2. Screenshots showing:
    • The application running in VS Code
    • Tests in the browser with different names
    • The counter incrementing
    • Reference: See screenshot examples
  3. Answer document to the comprehension questions
  4. Completed exercises (if requested)

Evaluation Criteria​

CriterionPoints
Project correctly created with Spring Initializr10%
Complete and functional Greeting and GreetingController classes30%
Application starts without error20%
Successful tests in the browser20%
Comprehension questions answered10%
Additional exercises (bonus)10%
Total100%

Additional Resources​

Documentation​

Video Tutorials​

Tools​

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 clean before mvn 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:

  1. Check the "Troubleshooting" section
  2. Check the logs in the console
  3. Search for the error on Stack Overflow
  4. Contact your teacher

Good work and happy coding!


Back to Module 2