SPRING BOOT @RestController
SPRING BOOT
@RestController is used to create Restful web services in Spring Boot applications.
Spring Boot @RestController annotation
➔ @RestController is an annotation in Spring Boot that defines a class as a request handler for API endpoints
Key characteristics of Spring Boot @RestController annotation:
➔ @RestController is a combination of the two annotations @Controller and @ResponseBody, so their functionality is now included in the @RestController annotation.
➔ This is the primary annotation for creating RESTful APIs and the main entry point for managing the API.
➔ @RestController is used at the class level and is a shorthand use of both the @Controller and @ResponseBody annotations. @ResponseBody ensures that return values should be bound directly to the HTTP response body.
➔ @RestController automatically returns values (mostly JSON or XML) in the HTTP response body, no view resolver is required to convert or serialize the data to JSON or XML. Unlike a standard @Controller annotation, the @RestController annotation does not use a view resolver mechanism and does not render HTML pages.
➔ @RestController returns formatted JSON or XML data to clients, such as mobile apps and front-end applications, instead of returning views like HTML pages.
➔ @RestController typically works in conjunction with other annotations like @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping to handle specific HTTP client requests.
➔ Any class marked with the @RestController annotation in Spring Boot is automatically scanned and registered by the Spring Boot system during component scanning.
Syntax
package com.exam.helloworld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String helloHandler() {
return "Hello World, Spring Boot is working fine.";
}
}
This example above shows that when a client accesses the /hello endpoint via an HTTP GET request, the api will return the string data "Hello, World" as a response via the HTTP response body
Best Practice:
➔ Separation of Concerns: @RestController should be implemented in classes that focus only on handling HTTP requests, rather than handling business logic. A separate service layer should be implemented to develop business logic. Data is required for business logic, so another data layer called a repository layer should also be implemented.
➔ Return type objects: In most cases, Java objects (single objects or lists of objects) need to be returned and Spring Boot can handle object-JSON serialization.
➔ HTTP Method Specific Mapping: Although it is possible to map any HTTP method using the simple @RequestMapping with the method attribute, for clarity it is better to use the HTTP method specific mappings @GetMapping (for http GET requests), @PostMapping (for http POST requests), @PutMapping (for http PUT requests), @DeleteMapping (for http DELETE requests).
➔ Exception Handling: @ControllerAdvice or @RestControllerAdvice annotations will be used to handle exceptions globally across all controllers to handle consistent error responses.
01 Open Spring Tool Suite (STS) IDE.
02 Create new project with Spring Starter Project.
Create porject in STS:
➔ name (Project Name): This is the name of the project as displayed in the development environment. It is optional, descriptive, and often uses the same name as artifactId. The project name can contain any mixed-letter words separated by hyphens. Spring Boot follows the Java naming convention.
➔ groupId: This identifier uniquely identifies the groupID across all projects. This can help avoid naming conflicts with other projects. The group ID can be viewed as a reserved Internet domain name, it does not necessarily have to be an actual domain name. The groupId can be named using any lowercase letter, separated by a dot (.), for example com.example, com.mydomain, etc.
➔ artifactId: This is the unique identifier and base name for the project within the groupId. This is usually the same as the project name in lowercase letters and is separated by a hyphen if there are multiple words. Spring Boot uses this name to create artifact files in .jar or .war format, for example hello-world-1.0.0.jar.
➔ packageName: This is the base Java package of the application and is used to organize the source code files. This helps avoid naming conflicts between classes in the application. The package name can be similar to a reserved domain name followed by words separated by dots. For example com.myexample.myapp, org.exam.app, com.exam.demo etc. By default Spring Boot uses groupId.arifactId as the package name and it is recommended to avoid using the default package name.
03 Provide information to the Spring Starter project.
04 Select dependency.
05 Create Controller.
06 Code for Controller.
07 Run HelloworldApplication.java
08 If there is a error like bellow, change the server default port.
09 Change the server default port in application.properties file.
10. After successfully run HelloworldApplication.java.
11. Test Restfull api in the browser. Type localhost:8090/hello in address bar of a browser.