Search code examples
spring-boot

Spring Boot RequestMapping does not work with Filter


I am developing a SpringBoot Project in which there is @RestController and FilterRegistrationBean.The filter I added works, but the url configured in @RestController and @RequestMapping does not work.When I request the url, the response code is 200, but no content showed.While I removed the filter, the RequestMapping worked fine.why? (The url I visited is http://localhost:8080/simple) Here is my code. SessionTokenFilter:

public class SessionTokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String[]> param_map = servletRequest.getParameterMap();
        for(String param_key: param_map.keySet()){
            System.out.println("Parameter name: "+param_key);
        }
        System.out.println("Get a request from the browser!");
    }
}

AppConfiguration.java

@Configuration
public class AppConfiguration {
    @Bean
    public FilterRegistrationBean<SessionTokenFilter> registerFilter(){
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(new SessionTokenFilter());
        filterBean.setUrlPatterns(Arrays.asList("/*"));
        return filterBean;
    }
}

ApiRouters.java

@RestController
public class ApiRouters {
    @RequestMapping(value="/simple", method= RequestMethod.GET)
    public ResponseEntity simple(){
        System.out.println("Simple url matched!");
        return ResponseEntity.ok().body("Ok");
    }
}

and the main entry class:

@SpringBootApplication
public class ApiApplication {
    public static void main(String[] args){
        SpringApplication.run(ApiApplication.class);
    }
}

Solution

  • The reason is that the filter chain should be called. When I added this line in the filter class, everything worked fine.

    filterChain.doFilter(servletRequest, servletResponse);