1. 程式人生 > >Java自定義註解實現許可權管理

Java自定義註解實現許可權管理

前言

原始碼

定義許可權註解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authority {

    String value() default "admin";
}

增加攔截器

public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws
Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); Authority authority = method.getAnnotation(Authority.class); if (authority == null) { // 如果註解為null, 說明不需要攔截, 直接放過 return true; } // 這裡為了方便直接傳遞了引數
// 一般的做法是使用者第一次登入,將資訊放到session中 // 以後每次操作時從request中獲取session,從session中獲取使用者資訊 // 然後根據使用者資訊從資料庫中查許可權資訊 String userAuthority = httpServletRequest.getParameter("userAuthority"); if (!userAuthority.equals("admin")) { // 脫離了Spring MVC的返回流程,重新編碼 httpServletResponse.setCharacterEncoding("utf-8"
); httpServletResponse.setContentType("application/json;charset=UTF-8"); PrintWriter out = httpServletResponse.getWriter(); out.print("沒有許可權"); out.flush(); out.close(); return false; } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }

配置攔截器

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthorityInterceptor()).addPathPatterns("/**");
    }
}

測試Controller

@RestController
public class UserController {

    // 這個是為了測試沒有註解時,是否會攔截
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public Map login() {
        Map<String, String> map = new HashMap<>();
        map.put("msg", "login success");
        return map;
    }

    @Authority()
    @RequestMapping(value = "queryAllProduct", method = RequestMethod.GET)
    public Map queryAllProduct() {
        Map<String, String> map = new HashMap<>();
        map.put("msg", "this is all data");
        return map;
    }
}

測試
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

參考部落格