0.基本概念
- AOP(Aspect-oriented programming)
In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'". This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality. AOP forms a basis for aspect-oriented software development.
在計算中,面向切片的編程(AOP)是一種編程范例,旨在通過允許分離橫切關注點來增加模塊性。它通過向現有代碼(建議)添加額外行為而不修改代碼本身,而是通過“切入點”規范分別指定修改哪些代碼,例如“當函數名稱以'set'開頭時記錄所有函數調用”。這允許將不是業務邏輯核心的行為(如日志記錄)添加到程序中,而不會混淆代碼和功能的核心。 AOP構成了面向切片的軟件開發的基礎。
1.問題描述
在web開發中會涉及到這樣一個基本問題,在用戶發出一個http請求時,需要驗證是否有權訪問(在本例中 為是否登錄)。若未登錄則需要跳轉到登錄頁面,否則響應用戶請求。
2.解決方案
1.在 maven 配置文件中 添加AOP依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.編寫驗證器
public class SignVerification {// 登錄驗證
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpSession session= request.getSession();
public boolean Verification(){
if (session.getAttribute("Admin") == null)
{
return false;
}
return true;
}
}
3.編寫攔截器 VerificationAspect
@Aspect
@Component // 放入spring 容器
public class VerificationAspect {
private final static Logger logger = LoggerFactory.getLogger(VerificationAspect.class);
//攔截條件
@Pointcut("execution(public * com.freeyun.demo.Controller.ShowInfoController.*(..))")
public void log() {}
@Around("log()")
public Object signVerification(ProceedingJoinPoint pjp) throws Throwable{
SignVerification v = new SignVerification();
if (v.Verification())//已經登錄
{
return pjp.proceed();//繼續執行被攔截的方法
}
else {//未登錄
//構建JSON
String response = "{\"signin\":0}";
return response;
}
}
}
4.前端對收到的JOSN數據進行判斷,若未登錄則跳轉到登錄頁面
if(response.signin == 0)
{
window.location.href = "登錄頁面的路徑";
}