Using Spring Interceptor or Using Servlet Filter How To Get a Request URL Template That Has Been Hit?

In this tutorial, 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

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example