先描述一下應用場景,基於Spring MVC的WEB程序,須要對每一個Action進行權限判斷,當前用戶有權限則容許執行Action,無權限要出錯提示。權限有不少種,好比用戶管理權限、日誌審計權限、系統配置權限等等,每種權限還會帶參數,好比各個權限還要區分讀權限仍是寫權限。css
想實現統一的權限檢查,就要對Action進行攔截,通常是經過攔截器來作,能夠實現HandlerInterceptor或者HandlerInterceptorAdapter,可是每一個Action都有不一樣的權限檢查,好比getUsers要用戶管理的讀權限,deleteLogs要日誌審計的寫權限,只定義一個攔截器很難作到,爲每種權限定義一個攔截器又太亂,此時能夠經過自定義註解來標明每一個Action須要什麼權限,而後在單一的攔截器裏就能夠統一檢查了。java
具體這麼作,先實現一個自定義註解,名叫AuthCheck:web
package com.test.web; import java.lang.annotation.Documented; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy; @Documented @Target(ElementType.METHOD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface AuthCheck { /** * 權限類型 * @return */ String type() default ""; /** * 是否須要寫權限 * @return */ boolean write() default false; }
這個註解裏包含2個屬性,分別用於標定權限的類型與讀寫要求。而後爲須要檢查權限的Action加註解,此處以getUsers和deleteLogs爲例,前者要求對用戶管理有讀權限,後者要求對日誌審計有寫權限,注意@AuthCheck的用法:spring
@AuthCheck(type = "user", write = false) @RequestMapping(value = "/getUsers", method = RequestMethod.POST) @ResponseBody public JsonResponse getUsers(@RequestBody GetUsersRequest request) { //具體實現,略 } @AuthCheck(type = "log", write = true) @RequestMapping(value = "/deleteLogs", method = RequestMethod.POST) @ResponseBody public JsonResponse deleteLogs(@RequestBody DeleteLogsRequest request) { //具體實現,略 }
最後要實現攔截器:cookie
package com.test.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 全局攔截器 */ public class ActionInterceptor implements HandlerInterceptor { /** * 前置攔截,用於檢查身份與權限 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //從傳入的handler中檢查是否有AuthCheck的聲明 HandlerMethod method = (HandlerMethod)handler; AuthCheck auth = method.getMethodAnnotation(AuthCheck.class); //找到了,取出定義的權限屬性,結合身份信息進行檢查 if(auth != null) { String type = auth.type(); boolean write = auth.write(); //根據type與write,結合session/cookie等身份信息進行檢查 //若是權限檢查不經過,能夠輸出特定信息、進行跳轉等操做 //而且必定要return false,表示被攔截的方法不用繼續執行了 } //檢查經過,返回true,方法會繼續執行 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView model) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { } }
攔截器要生效,還要配置一下:
session
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/js/**" /> <mvc:exclude-mapping path="/css/**" /> <bean class="com.test.web.ActionInterceptor" /> </mvc:interceptor> </mvc:interceptors>
OK,搞定收工。
mvc