Junior — Middle
What methods can be used to intercept or capture HTTP requests?
sobes.tech AI
Answer from AI
In Java, the following methods are commonly used to intercept HTTP requests:
-
Servlet Filters
- Allow intercepting requests and responses before they reach the servlet.
- Used for logging, authentication, modifying requests/responses.
-
Interceptors in JAX-RS or Spring
- In REST applications, Client or Server Interceptors can be used to handle requests and responses.
-
Aspect-Oriented Programming (AOP)
- In Spring AOP, you can create aspects that intercept controller method calls.
-
HttpServletRequestWrapper
- A wrapper around the request that allows modifying or analyzing the request content.
Example of using a filter:
@WebFilter("/*")
public class LoggingFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("Request: " + req.getMethod() + " " + req.getRequestURI());
chain.doFilter(request, response); // pass further
}
}
Thus, filters and interceptors are the main ways to intercept HTTP requests in Java.