如何在Spring Web应用程序中预处理所有请求? [英] How to preprocess all requests in Spring Web application?

查看:165
本文介绍了如何在Spring Web应用程序中预处理所有请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RESTful Spring应用程序,它可以处理各种控制器和各种 @RequestMapping -s的各种请求。

I have a RESTful Spring application, which can process various request with various controllers and various @RequestMapping-s.

现在我希望每个请求都包含一个用户/密码对,用户为用户 GET 参数?user = username 和密码密码 POST 参数。

Now I wish each request contain additionally a user/password pair, user as user GET parameter ?user=username and password in password POST parameter.

是是否可以在所有请求进入控制器并检查凭据和可能的返回认证错误之前对其进行预处理?

Is it possible to "preprocess" all requests before they go to controllers and check credentials and possible return authentication error?

这是一种机制,它是否为过滤器 ?

Is this a mechanism, which is caller "filters" or not?

推荐答案

有多种方法可以在请求进入控制器之前拦截这些请求。

There are couple of ways for intercepting the requests before they land into controllers.



  1. 使用Servlet过滤器:




    @WebFilter(urlPatterns = "path-to-intercept", filterName = "your-filter-name")
    public class MyRequestFilter implements Filter {
        init(...);
        doFilter(...);
        destroy(); 
    }





  1. 使用Spring HandlerIntecptors:




    public class MyRequestInterceptor extends HandlerInterceptorAdapter{

        preHandle(...); //called before the request lands to the controller.
        postHandle(...); //called after the controller method finishes execution.
        afterCompletion(...); //called before the response is sent.
    }

在您的配置中:

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/yourInterceptingPath/" />
            <bean class="path-to-your-Interceptor.MyRequestInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors> 

这篇关于如何在Spring Web应用程序中预处理所有请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆