先描述一下应用场景,基于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