簡體   English   中英

如何在Spring Web應用程序中預處理所有請求?

[英]How to preprocess all requests in Spring Web application?

我有一個RESTful Spring應用程序,該應用程序可以使用各種控制器和各種@RequestMapping -s處理各種請求。

現在,我希望每個請求還包含一個用戶/密碼對,用戶作為用戶GET參數?user=username以及密碼POST參數中的密碼。

是否可以在處理所有請求之前先對其進行“預處理”,然后再檢查憑據並可能返回身份驗證錯誤?

這是調用者“過濾器”與否的機制嗎?

有兩種方法可以在請求進入控制器之前攔截請求。

  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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM