0 day streak
java / beginner
Snippet

Returning JSON with @RestController

The @RestController annotation tells Spring that this class handles web requests and automatically converts the return value (like a Java object) into JSON format.

snippet.java
java
1
2
3
4
5
6
7
@RestController
public class MessageController {
@GetMapping("/hello")
public Message getMessage() {
return new Message("Hello, Spring!");
}
}
spring
Breakdown
1
@RestController
Marks the class as a web controller where every method returns a domain object instead of a view.
2
@GetMapping("/hello")
Maps HTTP GET requests to the /hello URL to this method.
3
public Message getMessage()
Returns a Java object which Spring converts to JSON automatically.