Using Spring Interceptor or Using Servlet Filter, how to get a Request URL template that has been hit?

In this section, we will learn how to find a request URL template that has been hit using Servlet Filter or Using Spring Interceptor. 

Before going to the example program just check the basis of the Servlet filter and Spring Interceptor.


The Servlet Filter is used to intercept the client request and do some pre-processing before they reach the DispatcherServlet. It can also intercept the response and do post-processing before sending to the client in web application.
On the other hand, The Spring Interceptor is only applied to requests that are sent to a Controller.

Get request URL template using Spring Interceptor(Good approach)

Demo Controller

@RequestMapping(path = "/user")
@RestController
public class UserController {

@GetMapping(path = "/{id}")
public ResponseEntity<Long>
getAllVariables(@PathVariable("id") Long id) {

return new ResponseEntity<Long>(id, HttpStatus.OK);

}
}

Custom Interceptor

@Component
public class RequestTemplateInterceptor
implements HandlerInterceptor {

@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object object, Exception arg3)
throws Exception {

}

@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object object, ModelAndView model)
throws Exception {

}

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object)
throws Exception {

String path = (String) request.
getAttribute(HandlerMapping.
BEST_MATCHING_PATTERN_ATTRIBUTE);
System.out.println("path : " + path);
return true;
}
}


Register it with InterceptorRegistry

@Component
public class AppConfig
implements WebMvcConfigurer {
@Autowired
RequestTemplateInterceptor requestTemplateInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestTemplateInterceptor);
}
}


Verify

> Run the Spring Boot application
> Hit the endpoint 'http://localhost:8080/user/8'

Console output: 

path : /user/{id}


Get request URL template using Servlet Filter

Custom Filter

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomFilter implements Filter {

@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO
try {
chain.doFilter(request, response);
} catch (Exception e) {
} finally {
String pattern = (String) request.
getAttribute(HandlerMapping.
BEST_MATCHING_PATTERN_ATTRIBUTE);
System.out.println("path: " + pattern);
}
}
}
Note* While using the Servlet filter you need to do the doFilter first before you try to do the call to getAttribute because that attribute will be set later in the request lifecycle.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete