2

I want to implement filter on my Spring Boot Rest API project but some how my filter not invoked. I have added below implementation for that.

public class AutorizationFilter implements Filter{
Logger log = LoggerFactory.getLogger(AutorizationFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    log.info("**** Start ****");

}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    log.info("**** doFilter ****");
    chain.doFilter(request, response);

}
@Override
public void destroy() {
    log.info("**** end ****");
}}

init and destroy method are working but doFilter method not invoke.

@Configuration
public class RestApiConfig {
@Bean
public FilterRegistrationBean<AutorizationFilter> filterRegistrationBean(){
    FilterRegistrationBean<AutorizationFilter> registrationBean = new FilterRegistrationBean<>();
    registrationBean.setFilter(new AutorizationFilter());
    registrationBean.addUrlPatterns("/**");
    return registrationBean;    
}}

My controller is as below:

@RestController 
@RequestMapping("/home")
public class HomeController {
@RequestMapping(value="/hello",method=RequestMethod.GET)
public ResponseEntity<Object> hello() {
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("data","called home controller");
return new ResponseEntity<>(resultMap,HttpStatus.OK);
 }
}

Any one please help me why dofilter method is not working.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Piyush Chaudhari
  • 812
  • 3
  • 17
  • 34
  • you just created a BEAN with filter, but did't apply it to application. Common thing is to use Spring security ```WebSecurityConfigurerAdapter``` and add filters inside. For more info use http://www.baeldung.com/spring-security-custom-filter – Mykhailo Voloshyn Jul 30 '18 at 12:12
  • @Mykhailo Voloshyn: So I can't use filter without Spring security? – Piyush Chaudhari Jul 30 '18 at 12:14
  • I suppose you can. But i don't have such experiance. Did you read this? https://stackoverflow.com/questions/19825946/how-to-add-a-filter-class-in-spring-boot – Mykhailo Voloshyn Jul 30 '18 at 12:19
  • 4
    finally i found the solution, I need to replace registrationBean.addUrlPatterns("/**") with registrationBean.addUrlPatterns("/*") and it's working fine for me. – Piyush Chaudhari Jul 30 '18 at 13:31
  • @PiyushChaudhari add your solution as an answer and accept it to help future readers. I had the same problem but almost didn't notice your comment. Thanks – Alexandru Severin Dec 09 '20 at 10:18

0 Answers0