spring Aop实现身份验证和springboot异常统一处理
生活随笔
收集整理的這篇文章主要介紹了
spring Aop实现身份验证和springboot异常统一处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章有不當之處,歡迎指正,如果喜歡微信閱讀,你也可以關注我的微信公眾號:好好學java,獲取優質學習資源。
一、spring Aop身份驗證
一般,如果用戶沒有登錄的話,用戶只可以查看商品,但是其他的,比如支付等是不能夠進行操作的,這個時候,我們就需要用到用戶攔截, 或者說身份驗證了。
首先定義一個類AuthorizeAspect,以@Aspect注解。
然后把所有以Controller聲明為切點,但排除UserController,因為這個Controller就是驗證用戶登錄的Controller。
@Pointcut("execution(public * com.sihai.controller *.*(..))"+"&& !execution(public * com.sihai.controller.UserController.*(..))")public void verify(){}最后對這個切點做一些前置處理,因為用戶登錄后,按照我們之前寫的邏輯,cookie和redis中應該含有用戶的信息,所以現在查詢這兩個地方,來驗證用戶有沒有登錄。
@Before("verify()")public void doVerify(){ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request=attributes.getRequest();//查詢cookieCookie cookie= CookieUtil.get(request,CookieConstant.TOKEN);if (cookie==null){log.warn("Cookie中查不到token");throw new AuthorizeException();}//去redis查詢,這個下面的redis用到的是springboot的redis工具類String tokenValue=redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if (StringUtils.isEmpty(tokenValue)){log.warn("Redis中查不到token");throw new AuthorizeException();}}完整代碼如下:
@Aspect @Component @Slf4j public class AuthorizeAspect {@Autowiredprivate StringRedisTemplate redisTemplate;@Pointcut("execution(public * com.sihai.controller. *.*(..))"+"&& !execution(public * com.sihai.controller. UserController.*(..))")public void verify(){}@Before("verify()")public void doVerify(){ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request=attributes.getRequest();//查詢cookieCookie cookie= CookieUtil.get(request,CookieConstant.TOKEN);if (cookie==null){log.warn(" Cookie中查不到token");throw new AuthorizeException();}//去redis查詢String tokenValue=redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if (StringUtils.isEmpty(tokenValue)){log.warn(" Redis中查不到token");throw new AuthorizeException();}}}二、springboot統一異常處理
- 自定義異常類
從以上代碼中可以看到,如果用戶沒有登陸,就會拋出一個 AuthorizeException的異常,這是一個自定義的異常。這個異常很簡單,只有一個簡單的定義,為運行時異常
public class AuthorizeException extends RuntimeException {}之后我們需要定義一個對這個異常的處理器 ExceptionHandler,當撲獲到這個異常,說明用戶沒有登陸,那就重新調到登陸界面(訪問處理登陸的Controller)。
- 創建全局異常處理類:通過使用@ControllerAdvice定義統一的異常處理類,而不是在每個Controller中逐個定義。@ExceptionHandler用來定義函數針對的異常類型,最后將Exception對象和請求URL映射到error.html中
- 實現error.html頁面展示:在templates目錄下創建error.html,將請求的URL和Exception對象的message輸出。
啟動該應用,訪問:http://localhost:8080/hello,可以看到如下錯誤提示頁面。
總結
以上是生活随笔為你收集整理的spring Aop实现身份验证和springboot异常统一处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实现支付宝支付完整过程(沙箱测试
- 下一篇: java使用websocket前后端通信