Help me please, or show other ways to resolve this problem.
@RestController
@RequestMapping("/users")
public class UserController {
    @RequestMapping("/login")
    public String logIn() {
        return "";
    }
    @RequestMapping("/getUserData")
    @FilterThisRequest
    public String getUserData(@PathVariable Long userId) {
        return user;
    }
}
And I have AuthFilter extends GenericFilterBean which makes a certain logic. How can I make that the filter execute only before methods which have @FilterThisRequest? Or there are better practices to resolve this problem?
Check FilterRegistrationBean reference guide at https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans.
Make FilterRegistrationBean available to Spring via a @Configuration class, the below example will ensure that authFilter runs only for /getUserData. Note that it is URL (and not method) based filtering.
@Autowired AuthFilter authfilter;
....
....
@Bean
public FilterRegistrationBean authFilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean(authfilter);
    registration.addUrlPatterns("/web-app-name/getUserData/");
    return registration;
}
                        I would suggest you for the Interceptor.
@Configuration 
public class Config extends WebMvcConfigurerAdapter {
@Autowired
RequestInterceptor requestInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestInterceptor).addPathPatterns("/getUserData","/user");
    }
}
Interceptor -
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object object) throws Exception {
}
You can override Interceptor's prehandle and postHandle according to your need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With