Spring Boot: What is Multi Request Mapping
In this post, we are going to discuss the concept of Multi Request Mapping. This topic comes into use when we have a requirement of calling the same method for different URLs.
So normally in spring boot while creating an API endpoint we simply use different annotations for defining the path and then declaring our methods.
RequestMapping = This annotation we can use at class level as well as method level. while we want a common starting point for all the endpoints we use this annotation at the top of the class.
Ex.
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/getCall")
public String getMessage() {
return "Hi From App!!";
}
}
Now /test will be used before all the method paths.
Now the scenario comes where we want to define multiple endpoints for one method.
@RequestMapping("/")
@RequestMapping("/get")
public String getMessage() {
return "Hi From App!!";
}
Now if you do so it will give the below error It is clearly saying with one method we can have only one RequestMapping annotation.
org.springframework.web.bind.annotation.RequestMapping is not a repeatable annotation type
Now if we see RequestMapping internals we can see it is taking an array of paths and the default is an empty string.
So if change our method like this it will allow both paths.
@RequestMapping({"/", "/get"})
public String getMessage() {
return "Hi From App!!";
}
Now we hit URL: http://localhost:8080/test/get or http://localhost:8080/test/ It will call the same method.
So now based on the Path we can call the same method and then based on the Path params we can have conditions inside our method.
Ex.
@RequestMapping({"/", "/get"})
public String getMessage(HttpServletRequest request) {
String path = request.getRequestURI();
String last4 = path.substring(path.length() - 4);
if (last4 == "/get" ){
//do something
}else {
//do something else
}
System.out.println("Path = "+path);
return "Hi From App!!";
}
So this is all about Multi Request mapping and their usage in spring boot.
Next, I am starting a tutorial series on Micronaut. So follow for more learning.
Thanks for reading!!