Spring Boot is a popular framework for building Java applications. It provides a lot of pre-configured components to help developers get started quickly, including HTTP request interceptors. In this blog post, we will cover the basics of HTTP request interceptors and how to use them in Spring Boot.
What are HTTP Request Interceptors?
An HTTP request interceptor is a component that intercepts incoming HTTP requests before they reach their intended destination. The interceptor can manipulate the request, add or remove headers, modify the body, or even cancel the request before it reaches its destination. HTTP request interceptors are useful in situations where you need to add common functionality to multiple requests, such as logging, authentication, and authorization.
How to create a Spring Boot HTTP Request Interceptor
Step 1: Create a new project
Create a new project using Spring Initializer. Choose the Spring Boot version and select the Web and Lombok dependencies.
Step 2: Implement the Interceptor
Create a new class that implements the HandlerInterceptor
interface. The interface has three methods: preHandle
, postHandle
, and afterCompletion
. The preHandle
method is called before the request is processed, the postHandle
method is called after the request has been processed, and the afterCompletion
method is called after the response has been sent.
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("Request URL: {}", request.getRequestURL());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//Do Nothing
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//Do Nothing
}
}
Step 3: Register the Interceptor
Create a new configuration class and use the addInterceptors
method to register the interceptor.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private RequestInterceptor requestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor);
}
}
Step 4: Test the Interceptor
Start the application and make a request to see if the interceptor is logging the URL.
2022-12-01 11:13:13.567 INFO 14072 --- [nio-8080-exec-1] c.e.s.RequestInterceptor
Customizing Request and Response
One of the key benefits of using HTTP request interceptors is the ability to customize the request and response. You can add or remove headers, modify the body, or even cancel the request before it reaches its destination. Let’s take a look at how you can customize the request and response in your HTTP request interceptor.
Modifying the Request
To modify the request, you can access the HttpServletRequest
object in the preHandle
method and make changes as needed. For example, you can add a header to the request like this:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("Request URL: {}", request.getRequestURL());
request.setAttribute("requestStartTime", System.currentTimeMillis());
return true;
}
In the example above, we are adding a new header requestStartTime
to the request and setting it to the current time in milliseconds. This can be useful for logging or debugging purposes.
Modifying the Response
To modify the response, you can access the HttpServletResponse
object in the postHandle
method and make changes as needed. For example, you can add a header to the response like this:
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long requestStartTime = (long) request.getAttribute("requestStartTime");
long requestEndTime = System.currentTimeMillis();
log.info("Request Time: {}ms", requestEndTime - requestStartTime);
response.addHeader("requestTime", String.valueOf(requestEndTime - requestStartTime));
}
In the example above, we are accessing the requestStartTime
header that we set in the preHandle
method and adding a new header requestTime
to the response with the difference between the current time and the requestStartTime
.
Cancelling the Request
In some cases, you may want to cancel a request before it reaches its destination. To do this, simply return false
from the preHandle
method. For example:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!request.getHeader("Authorization").equals("secret")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return false;
}
return true;
}
In the example above, we are checking the Authorization
header in the request. If it does not equal "secret"
, we send a 401 Unauthorized
error to the client and return false
to cancel the request.
Conclusion
In this section, we covered how to customize the request and response in your HTTP request interceptors. Whether you want to add headers, modify the body, or cancel the request, the preHandle
and postHandle
methods provide the necessary tools to do so. With these capabilities, you can easily add common functionality to multiple requests in your Spring Boot application.