REST Controller (GreetingController)
Relevant source files
The following files were used as context for generating this wiki page:- complete/src/main/java/com/example/restservice/GreetingController.java
- complete/src/main/java/com/example/restservice/Greeting.java
- README.adoc
- complete/src/test/java/com/example/restservice/GreetingControllerTests.java
- complete/src/main/java/com/example/restservice/RestServiceApplication.java
- complete/pom.xml
The GreetingController is a RESTful web service controller built using the Spring Framework. Its primary purpose is to handle HTTP GET requests at the /greeting endpoint. The controller generates a "Hello, World" style greeting, which can be customized via a request parameter. It returns the greeting as a JSON object.
This controller demonstrates a fundamental concept in Spring's approach to building REST services, where an incoming HTTP request is mapped to a method that returns a domain object. This object is then automatically serialized into JSON and sent back in the HTTP response body. The entire service is bootstrapped by the RestServiceApplication class.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java, complete/src/main/java/com/example/restservice/RestServiceApplication.java
Architecture and Core Components
The GreetingController is a simple, self-contained component that relies on several key Spring annotations to function.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:8-17
Component Breakdown
| Component | Annotation/Type | Description | File |
|---|---|---|---|
GreetingController | @RestController | A Spring annotation that marks the class as a controller where every method returns a domain object instead of a view. It's a shorthand for @Controller and @ResponseBody. | GreetingController.java:8 |
greeting() | @GetMapping("/greeting") | A method that handles HTTP GET requests to the /greeting path. | GreetingController.java:14 |
counter | AtomicLong | A thread-safe counter used to generate unique IDs for each greeting request. | GreetingController.java:12 |
template | String | A static string template used to format the greeting message. | GreetingController.java:11 |
The following class diagram illustrates the relationship between the controller and its data model.
This diagram shows that GreetingController creates instances of the Greeting record.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java, complete/src/main/java/com/example/restservice/Greeting.java
API Endpoint: /greeting
The controller exposes a single endpoint for generating greetings.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:14-17
Request Details
- Path:
/greeting - HTTP Method:
GET - Description: Returns a JSON object representing a greeting.
Request Parameters
The endpoint accepts one optional query parameter.
| Parameter | Type | Description | Annotation | Default Value |
|---|---|---|---|---|
name | String | The name to include in the greeting message. | @RequestParam | "World" |
This is configured in the greeting method signature:
// complete/src/main/java/com/example/restservice/GreetingController.java:15
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name)
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:15, README.adoc
Response Details
The endpoint returns a JSON object with a 200 OK status. The structure of the JSON is defined by the Greeting record.
Response Body: Greeting Object
| Field | Type | Description |
|---|---|---|
id | long | A unique identifier for the greeting, incremented with each request. |
content | String | The textual representation of the greeting. |
Example Response (without name parameter):
{"id":1,"content":"Hello, World!"}
Example Response (with name=User parameter):
{"id":2,"content":"Hello, User!"}
Sources: README.adoc, complete/src/main/java/com/example/restservice/Greeting.java
Data Flow and Logic
The following sequence diagram illustrates the process from a client request to the server response.
This diagram shows how an incoming GET request is routed by the Spring Framework to the GreetingController, which then creates a Greeting object and returns it. Spring's message converters (Jackson) handle the JSON serialization automatically.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:14-17, complete/pom.xml:21-24
The internal logic of the greeting() method is as follows:
This flow shows the decision logic for handling the name parameter and the steps to construct the response.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:15-16
Testing
The GreetingController is tested using Spring's MockMvc. The tests verify that the controller returns the expected JSON response for requests both with and without the name parameter.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java
Test Scenarios
-
noParamGreetingShouldReturnDefaultMessage(): This test performs a GET request to/greetingwithout any parameters and asserts that the response status is200 OKand the JSON content is"Hello, World!".// complete/src/test/java/com/example/restservice/GreetingControllerTests.java:31-34 @Test public void noParamGreetingShouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk()) .andExpect(jsonPath("$.content").value("Hello, World!")); } -
paramGreetingShouldReturnTailoredMessage(): This test performs a GET request to/greetingwith the parametername=Spring Communityand asserts that the response status is200 OKand the JSON content is"Hello, Spring Community!".// complete/src/test/java/com/example/restservice/GreetingControllerTests.java:37-41 @Test public void paramGreetingShouldReturnTailoredMessage() throws Exception { this.mockMvc.perform(get("/greeting").param("name", "Spring Community")) .andDo(print()).andExpect(status().isOk()) .andExpect(jsonPath("$.content").value("Hello, Spring Community!")); }
The @SpringBootTest and @AutoConfigureMockMvc annotations are used to load the full application context and configure MockMvc for testing the web layer.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:26-27
Summary
The GreetingController serves as a concise and effective example of a REST controller in a Spring Boot application. It demonstrates how to map HTTP requests, handle query parameters with default values, manage state with a thread-safe counter, and return a structured JSON response. The automatic JSON serialization provided by the spring-boot-starter-web dependency and the straightforward testing with MockMvc highlight the productivity benefits of the Spring ecosystem.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java, complete/pom.xml:21-24