REST Controller
The rest controller is to handle the requests, defining the endpoints – REST APIs to handle the requests. We’ve taken only a GET mapping for the simplicity of this example.
- When the endpoint – /api/students are hit, it makes a list of mentioned 3 students and returns the list.
Code
Java
import com.w3wiki.requestInterceptor.Entity.Student; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping ( "/api" ) public class RESTController { // Return a list of students @GetMapping ( "/students" ) public List<Student> getStudents(){ // Add Data to POJO Student student1 = new Student( 1 , "Adwitiya" , "Mourya" ); Student student2 = new Student( 2 , "David" , "Goggins" ); Student student3 = new Student( 3 , "Andrew" , "Huberman" ); // Create a new List List<Student> myList = new ArrayList<Student>(); // Add Data to the list myList.add(student1); myList.add(student2); myList.add(student3); return myList; } } |
Spring Boot – Interceptor
Spring Boot Interceptor is an additional component that will intercept every request and response dispatch and perform some operations on it.
Interceptors in web applications play a major in performing initial or finalization work.
Interceptors have one primary purpose – “To intercept an incoming or outgoing request”.
This intercepting behavior is done to perform some operation BEFORE or AFTER an action invocation. You can think of an interceptor as a mediator between the request and the business logic reserved for that request. Interceptor in Spring Boot can be implemented either by extending the HandlerInterceptorAdapter class or by implementing HandlerInterceptor Interface.
Interceptors are useful for many purposes some of which are listed below :
1. Logging
Logging is a common practice to understand the flow of code & debugging. Interceptors are widely for the same, Documenting or recording the requests made by the client or the responses sent back to them is generally useful in debugging and monitoring purposes.
2. Authentication
Authentication is a security mechanism that can be implemented inside an Interceptor before the request even reaches its appropriate controller. It can be intercepted by the Interceptor & authentication can be verified, if denied then the request doesn’t get delegated to the controller which not only minimizes the code but reduces a great overhead.
3. Request/Response Modification
Interceptors are also used for modifying requests & responses. It can be done in the following ways :
- Adding or modifying request parameters
- Modifying request headers, or response head
- Change status code
- Redirection to a different URL
- Handle custom error requests/responses which frees the controller or an addition of an external component just to handle the exceptions.
Contact Us