1

I have Spring web application. I would like to put some common piece of code which will be executed at the beginning of each HTTP request so that I can check for spams. I have configured DispatcherServlet in my web.xml which means DispatcherServlet is the first entry point for every HTTP request. My question is does DispatcherServlet provide any method which will be executed first and then the control passes onto the requested annotation controller?

4

3 回答 3

4

我同意戴夫。您正在寻找的是映射 url 上所有请求的过滤器/拦截器。传统上,这是使用ServletFilter完成的。这是您放置自定义代码的地方。例如。

   public FooFilter implements ServletFilter {
    @Override
    void doFilter(ServletRequest request,
              ServletResponse response,
              FilterChain chain)
              throws IOException,
                     ServletException {
        // My Custom check for spam.
    }
}

一旦你在 ServletFilter 中实现了你的自定义代码,你所需要的就是在 web.xml 中配置它。

<filter>
    <filter-name>FooFilter</filter-name>
    <filter-class>com.foo.servlet.filters.FooFilter</filter-class>
    <init-param>
        <param-name>test-param</param-name>
        <param-value>Test parameter.</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>FooFilter</filter-name>
    <url-pattern>/*</url-pattern> <!-- The URL to be filtered. -->
</filter-mapping>

它是配置过滤器和拦截 Web 请求的最简单方法。

当使用 Spring 框架时,您会想要使用 Sping 的 HandlerInterceptor。一个很好的帖子,关于何时使用可以在这里找到的内容。

希望这可以帮助。

于 2012-06-18T23:56:13.280 回答
3

IMO 这种功能属于HandlerInterceptor(ref docs)

于 2012-06-18T23:24:42.810 回答
0

Servlet 过滤器会起作用,因为过滤器总是比任何 servlet 都先执行。过滤器将在 Dispatcher servlet 之前执行,但拦截器将在 Dispatcher servlet 之后和实际处理程序之前执行!

于 2016-02-17T16:54:07.843 回答