首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring MVC 實現基於註解的權限驗證:HandlerInterceptor 實戰

     編輯:Java 相關知識

核心機制:HandlerInterceptor

Spring MVC 提供 HandlerInterceptor 介面,三大切點:

  • preHandle:Controller 執行前,回傳 true 放行,false 截斷
  • postHandle:Controller 執行後、視圖渲染前
  • afterCompletion:視圖渲染後

實務上繼承 HandlerInterceptorAdapter 僅覆寫所需方法。

步驟 1:自定義權限註解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface AuthPassport {
    boolean validate() default true; // false 表示跳過驗證
}

步驟 2:實作攔截器

public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AuthPassport auth = hm.getMethodAnnotation(AuthPassport.class);
            if (auth == null || !auth.validate()) return true; // 無註解或標註跳過

            // 此處實作實際權限邏輯,例如檢查 Session/Token
            boolean hasPermission = checkPermission(request); // 自行實作
            if (hasPermission) return true;

            // 驗證失敗:重導向登入頁
            response.sendRedirect(request.getContextPath() + "/account/login");
            return false;
        }
        return true;
    }
}

步驟 3:Spring 配置掛載攔截器

<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
    <bean class="com.demo.web.auth.AuthInterceptor"/>
</mvc:interceptors>

步驟 4:Controller 掛載註解

@Controller
@RequestMapping("/helloworld")
public class HelloWorldController {
    @AuthPassport
    @RequestMapping({"/index", "/hello"})
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("message", "Hello World!");
        return mv;
    }
}

驗證效果

未登入訪問受保護頁面 → 自動跳轉 /account/login;登入後正常顯示。註解式聲明讓權限控制清晰可維護。

擴展建議

  • 結合 Spring Security 實現 RBAC/ACL 細粒度控制
  • 攔截器中整合 Redis 分散式 Session
  • 區分 AJAX 請求回傳 JSON 401 而非重導向
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved