SPRING BOOT @GetMapping
SPRING BOOT
The @GetMapping annotation is used to map an HTTP GET request URL to a specific Java method in a controller.
Spring Boot @GetMapping annotation
➔ @GetMapping is an annotation in Spring Boot that is used to create API endpoints for http GET requests for specific handler methods in a controller.
Key points of Spring Boot @GetMapping annotation:
➔ This annotation only works at the method level of a controller.
➔ This @GetMapping annotation only handles HTTP GET requests.
➔ If @RequestMapping is used for class level, then the final api (/api/users) will be created by adding the method level api (for example @GetMapping("/users")) to the class level api (for example @RequestMapping("/api")).
➔ Multiple URLs can be handled in a single method using a string array in the value or path attribute, for example, @GetMapping(value={"/url1","/url2"}).
Syntax
/* all are equivalent. */
@GetMapping({"/users", "/myusers", "/ourusers"}) or
@GetMapping(value={"/users", "/myusers", "/ourusers"}) or
@GetMapping(path={"/users", "/myusers", "/ourusers"})
➔ The value and path attributes in the @GetMapping annotation are aliases of each other, and there is no difference in functionality between them, and one can be used instead of the other.
Syntax
/* All are equivalent. */
@GetMapping("/users") or
@GetMapping(value = "/users") or
@GetMapping(path = "/users")
➔ The @GetMapping annotation endpoint only matches the HTTP GET method. The same functionality can be implemented using the @RequestMapping and method attributes to explicitly map the HTTP GET method (for example @RequestMapping(method="RequestMethod.GET")).
@GetMapping supports attributes to match the requested url
➔ params: Narrow down mappings based on the presence, absence, or value of a specific request parameter.
Syntax
Example: @GetMapping(value = "/users", params = "name")
➔ headers: It checks the presence, absence, or value of specific HTTP headers for specific request headers.
Syntax
Example: @GetMapping(value = "/users", headers="name=john")
➔ consumes: This specifies which media types will be consumed by the controller method from the request body. This is very unlikely in the case of @GetMapping because GET requests usually have no body. The attribute is available anyway.
➔ produces: This specifies what type of media should be produced and sent as a response to the client by the controller.
Syntax
Example: @GetMapping(value = "/users", produces="application/xml")
Example: @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
Example: @GetMapping(value = "/users", produces = {"application/json", "application/xml"})
@GetMapping handles dynamic URLs using @PathVariable.
➔ For example, @GetMapping("/hello/{id}") can work with handlerName(@PathVariable Long id) to handle dynamic URLs.
Request URL is localhost:8090/users/hello/101
Note: Here '/users' is the class level request mapping.
Syntax
@GetMapping(value="/hello/{id}")
public String helloHandler(@PathVariable Long id) {
return "GetMapping & PathVariable is working fine, ID="+id;
}
@GetMapping handles request parameters using @RequestParam.
➔ For example, @GetMapping(/hello) can work with handlerName(@RequestParam(name = "name") String name) to handle query parameters.
The request URL is localhost:8090/users/hello?name=john
Note: Here '/users' is the class level request mapping.
Syntax
@GetMapping(value="/hello")
public String helloHandler(@RequestParam("name") String n) {
return "GetMapping & RequestParam is working fine, name="+n;
}
Common usage and best practices:
➔ @GetMapping typically returns data such as a String, a Java object, or a list of Java objects, which Spring Boot automatically converts to the appropriate response format.
➔ @GetMapping is a short form of @RequestMapping(method="RequestMethod.GET")) and @GetMapping is a more specific, readable, and recommended way to implement HTTP GET requests.
Now practice this chapter in your learning environment.
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.
Request URL is /users/hello
Syntax
package com.exam.helloworld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
public class HelloController {
@GetMapping(value="/hello")
public String helloHandler() {
return "GetMapping is working fine";
}
}
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/users/hello in address bar of a browser.
Example @PathVariable
package com.exam.helloworld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
public class HelloController {
@GetMapping(value="/hello/{id}")
public String helloHandler(@PathVariable Long id) {
return "GetMapping & PathVariable is working fine, ID="+id;
}
}
@PathVariable output
Example @RequestParam
package com.exam.helloworld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
public class HelloController {
@GetMapping(value = "/hello")
public String helloHandler(@RequestParam("name") String n) {
return "GetMapping & RequestParam is working fine, name=" + n;
}
}
@RequestParam output