Use shouldNotFilter to exclude URLs for a Filter

Jira ticket:
http://jira.baeldung.com/browse/BAEL-4703

The existing article uses an out-dated way is used to excluded filtering
for certain urls, instead shouldNotFilter should be used.
This commit is contained in:
Tapan Avasthi 2021-01-02 04:03:44 +05:30
parent 187aa4031b
commit 71bbdb7fed
1 changed files with 20 additions and 17 deletions

View File

@ -12,19 +12,22 @@ import java.io.IOException;
@Order(1) @Order(1)
public class HeaderValidatorFilter extends OncePerRequestFilter { public class HeaderValidatorFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(HttpServletRequest request,
throws ServletException, IOException { HttpServletResponse response,
String path = request.getRequestURI(); FilterChain filterChain)
if ("/health".equals(path)) { throws ServletException,
filterChain.doFilter(request, response); IOException {
return;
}
String countryCode = request.getHeader("X-Country-Code"); String countryCode = request.getHeader("X-Country-Code");
if (!"US".equals(countryCode)) { if (!"US".equals(countryCode)) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid Locale"); response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid Locale");
return; return;
} }
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
return "/health".equals(path);
}
} }