Spring @RequestMapping Annotation Example
In this section we will learn about @RequestMapping Annotation.
@RequestMapping is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping
can be applied to the controller class as well as methods.
It has the following optional options
- name: Assign a name to this mapping.
- value: The primary mapping expressed by this annotation.
- method: The HTTP request methods to map to
- headers: The headers of the mapped request, narrowing the primary mapping.
@Controller
@RequestMapping("/employees")
public class EmployeeController {
@RequestMapping("/employee")
public String getEmployee() {
}
}
A @RequestMapping
on the class level is not required. Without it, all paths are simply absolute, and not relative.
This means if you specify the class level annotations, the URL shall be relative, it shall be http://localhost:8080/employees/employee
(URL to Handler mapping) and likewise.
@Controller
public class EmployeeController {
@RequestMapping("/employee")
public String getEmployee() {
}
}
Now, in this case, the URI path for the getEmployee()
handler method is absolute http://localhost:8080/employee
Project Directory
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-requestmapping-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-requestmapping-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
EmployeeController.java
package com.knf.dev.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@RequestMapping("/employee")
public String getEmployee() {
return "Employee";
}
}
Run Application - Application.java
mvn spring-boot:run
Try to send a GET request to the http://localhost:8080/employees/employee
endpoint using Postman.