注解的用法

1.用于切面编程

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public  @interface SystemServiceLog {

    String description()  default "";


}
@Pointcut("@annotation(com.gidoor.zcwd.web.annotation.SystemServiceLog)")
public  void serviceAspect() {
}
@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
2.用于拦截

/**
 * 权限限制
 * @author  2015-12-12 18:29:02
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PermessionLimit {
   
   /**
    * 登录拦截 (默认拦截)
    */
   boolean limit() default true;

}

/**
 * 权限拦截, 简易版
 * @author  2015-12-12 18:09:04
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter {
   
   
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      
      if (!(handler instanceof HandlerMethod)) {
         return super.preHandle(request, response, handler);
      }
      
      if (!ifLogin(request)) {
         HandlerMethod method = (HandlerMethod)handler;
         PermessionLimit permission = method.getMethodAnnotation(PermessionLimit.class);
         if (permission == null || permission.limit()) {
            response.sendRedirect(request.getContextPath() + "/toLogin");
            //request.getRequestDispatcher("/toLogin").forward(request, response);
            return false;
         }
      }
      
      return super.preHandle(request, response, handler);
   }
   
}

@RequestMapping("/toLogin")
@PermessionLimit(limit=false)
public String toLogin(Model model, HttpServletRequest request) {
   if (PermissionInterceptor.ifLogin(request)) {
      return "redirect:/";
   }
   return "login";




你可能感兴趣的:(java)