#Springboot filter not working

5 messages · Page 1 of 1 (latest)

granite horizon
#

So I want to add a filter to all the endpoints of my application that capture a header and logs the value of this header. I've started with this filter
`
@Component
@Slf4j
public class RequestHeaderFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestHeaderValue = httpRequest.getHeader("RequestHeader");

    log.info("The header value is" + requestHeaderValue);
    chain.doFilter(request, response);
}

}`

I'm using Java 17 and Springboot 2.6.5, Spring v5.3.17

The first problem I encountered is that I should be importing from import javax.servlet.*; but apparently I need to add the dependency manually to my pom.xml like this

<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>

This seemed weird for me because all the examples of filters I've found on Google never mention to manually add the dependency like this, but after uptading the pom.xml it seems the interface "Filter" I'm implementing is working but now every time im calling and endpoint through Postman, adding this "RequestHeader" header, I believe the filter is not being created, since adding a breakpoint to this filter and trying to debug it is never stopping on this breakpoint.

crisp hamletBOT
#

This post has been reserved for your question.

Hey @granite horizon! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

granite horizon
#

Also, in some examples I've seen that people are registering this filter in order to only apply the filter to some endpoints, but since I want this filter to be applied to all endpoints by default, it seems that it should be enough just annotating this filter with @Component

viscid pilot
#

@granite horizon You're close, you want @WebFilter not @Component,

I'd recommend having the class extend OncePerRequestFilter, just to help prevent multiple calls. You'll just swap to using
doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain)

Then you you'll want an @Configuration with @ServletComponentScan somewhere.