在請求處理之前,我有一個HandlerInterceptor執行一些自定義授權的實作。需要為每個端點調整授權程式。我使用HttpServletRequest::getMethodandHttpServletRequest::getRequestURI方法來推斷哪個端點被請求擊中,并且一切都按預期作業。
但是我不太喜歡在字串上使用containsandequals方法來執行手動匹配。有沒有更優雅的方式來做到這一點?我希望能夠執行以下操作:
boolean isMethodMatched = request.matches("FooController::getFoo");
該matches方法會將請求物件的實際請求 URL 和 HTTP 方法與 FooController 的 getFoo 方法宣告的方法進行比較。基本上它將是路由的復制,但沒有呼叫在攔截器完成其作業后將呼叫的方法。Spring Boot中有類似的東西嗎?
uj5u.com熱心網友回復:
handlerin 引數HandlerInterceptor#preHandle()實際上是HandlerMethod請求是否由帶注釋的控制器方法處理的實體。所以你最好的選擇是將它投射到HandlerMethod實體并圍繞它進行游戲。例如,它允許您獲取Method用于處理請求的實際實體,這是實作匹配邏輯的良好起點。
public class FooHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
Method controllerMethod = hm.getMethod();
//Then play around the controllerMethod at here.
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/513226.html
標籤:爪哇春天弹簧靴弹簧MVC
