Spring Boot RequestMapping不适用于过滤器

时间:2019-11-24 08:50:05

标签: spring-boot

我正在开发一个SpringBoot项目,其中有@RestController和FilterRegistrationBean。我添加的过滤器可以使用,但是在@RestController和@RequestMapping中配置的网址不起作用。当我请求该网址时,响应代码为200但没有显示任何内容。虽然我删除了过滤器,但RequestMapping正常运行。为什么? (我访问的网址是http://localhost:8080/simple) 这是我的代码。 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");
    }
}

和主条目类:

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

1 个答案:

答案 0 :(得分:2)

原因是应该调用过滤器链。 当我在过滤器类中添加代码时,一切正常。

filterChain.doFilter(servletRequest, servletResponse);