日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring Aop实现身份验证和springboot异常统一处理

發布時間:2025/3/20 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中
@ControllerAdvice public class ExceptionHandler {@Autowiredprivate ProjectUrlConfig projectUrlConfig;//攔截登錄異常@ExceptionHandler(value = AuthorizeException.class)public ModelAndView handlerAuthorizeException(){ModelAndView mav = new ModelAndView();mav.addObject("exception", e);mav.addObject("url", req.getRequestURL());mav.setViewName(DEFAULT_ERROR_VIEW);return mav;} }
  • 實現error.html頁面展示:在templates目錄下創建error.html,將請求的URL和Exception對象的message輸出。
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8" /><title>統一異常處理</title> </head> <body><h1>Error Handler</h1><div th:text="${url}"></div><div th:text="${exception.message}"></div> </body> </html>

啟動該應用,訪問:http://localhost:8080/hello,可以看到如下錯誤提示頁面。

總結

以上是生活随笔為你收集整理的spring Aop实现身份验证和springboot异常统一处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。