在Spring Boot中未调用ServletFilter

时间:2018-12-21 10:02:15

标签: spring-boot


我需要在调用Servlet时执行Servlet过滤器。 这是我的过滤器定义:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestFilter implements Filter {


    @Bean
    public FilterRegistrationBean<RequestFilter> loggingFilter(){
        FilterRegistrationBean<RequestFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RequestFilter());
        registrationBean.addUrlPatterns("/myServlet");

        return registrationBean;
    }


    @Override
    public void doFilter(
            ServletRequest request,
            ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        System.out.println("Called request " + req.getRequestURI());
        chain.doFilter(request, response);
        System.out.println("Response :" + res.getContentType());
    }


}

我观察到的是,当我调用/ myServlet URL时,仅激活Servlet,而不激活过滤器。 这是我注册我的DemoServlet的方式:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
    @Autowired
    private DemoServlet myServlet;
    @Bean
    public ServletRegistrationBean<DemoServlet> myServletBean()
    {
        ServletRegistrationBean<DemoServlet> servlet = new ServletRegistrationBean<>();
        servlet.setServlet(myServlet);
        servlet.addUrlMappings("/myServlet");
        return servlet;
    }

}

在网上可用的示例中,我仅发现在REST调用时激活了过滤器。是否可以为特定的Servlet激活过滤器?

0 个答案:

没有答案