简介:本文将介绍如何使用面向切面编程(AOP)技术实现一个简单的权限管理系统demo。我们将使用ssm框架作为基础,通过AOP来拦截和处理权限相关的操作。主要实现拦截操作。(如有需要,您可以自行从Gitee仓库中获取。仔细研究,主要用于学习AOP切面编程)
一、环境配置
引入Spring相关依赖
在pom.xml文件中添加以下依赖:
<!--AOP联盟--><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version></dependency><!--Spring Aspects--><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.0.2.RELEASE</version></dependency><!--aspectj--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.3</version></dependency><!-- mybatis核心包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!-- mybatis/spring包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><!-- 导入Mysql数据库链接jar包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.36</version></dependency>
二、定义用户实体类
public class User {private Integer id;private String userTel;private String userPsw;private String userName;private String userSex;private String userBirthday;private String userAddress;private String userIdName;private String userIDNum;// 省略getter和setter方法
}
三、定义权限类
public class SysPerssion {private Integer id;private String permissionName;private String permissionUrl;private String permissionStr;//省略getter和setter方法
}
四、创建自定义注解
import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresPermission {String[] value();
}
五、创建权限切面类
最主要的类(要在对应的xml文件中开启aop自动配置)
import com.javen.model.SysPerssion;
import com.javen.service.SysPermissionService;
import com.javen.util.UserInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;@Component
@Aspect
public class PermissionAspect {@Autowiredprivate SysPermissionService sysPermissionService;@Autowiredprivate HttpSession httpSession;@Autowiredprivate HttpServletRequest request;/*** 根据Cookie获取userId*/@Before("@annotation(requiresPermission)")public void checkPermission(JoinPoint joinPoint, RequiresPermission requiresPermission) {// 从数据库中获取当前用户的权限,判断是否包含注解指定的权限Integer userId = null;Cookie[] cookies = request.getCookies();for(Cookie cookie : cookies){userId = UserInfo.getInfo(cookie.getValue());}// 根据用户ID从数据库获取用户的所有权限List<SysPerssion> userPermissions = sysPermissionService.getAllPermissionsById(userId);System.out.println(userPermissions);// 获取具体权限String[] requiredPermissions = requiresPermission.value();// 进行权限匹配操作,判断用户是否具有执行操作所需的权限boolean hasPermission = Arrays.stream(requiredPermissions).anyMatch(requiredPermission -> userPermissions.stream().anyMatch(permission -> permission.getPermissionStr().equals(requiredPermission)));if (!hasPermission) {// 如果权限不足,可以抛出异常或执行其他相应的处理逻辑throw new SecurityException("权限不足");}}
}
六、编写登录接口
@Controller
@RequestMapping("/user")
public class UserController { private static Logger log=LoggerFactory.getLogger(UserController.class);@Resource private IUserService userService; @Resourceprivate HttpSession session;@RequestMapping(value="/login")public String test2(User user, Model model, HttpServletResponse response) throws Exception{User u = userService.login(user);if(u == null){// todo}else{// 账户密码正确Random random = new Random();int i = random.nextInt();Cookie cookie = new Cookie("userInfo",i + "abc");cookie.setPath("/");UserInfo.putInfo(i + "abc",user.getId());response.addCookie(cookie);log.info("cookie 执行:" + i + "abc");session.setAttribute(i+"abc",user.getId());}log.info(user.toString());model.addAttribute("user", user);return "index";}
}
七、编写测试接口类
在要拦截的接口上方添加 @RequiresPermission() 注解
@Controller
@RequestMapping("test")
public class TestController {@Autowiredprivate HttpSession httpSession;@RequestMapping("index")@RequiresPermission({"select"})public String index(HttpServletRequest request){//测试获取cookieCookie[] cookies = request.getCookies();for(Cookie cookie : cookies){System.out.println(cookie.getName() + "=" + cookie.getValue());}Enumeration<String> attributeNames = httpSession.getAttributeNames();while (attributeNames.hasMoreElements()){String s = attributeNames.nextElement();System.out.println(s);System.out.println("getId="+httpSession.getAttribute(s));}return "index";}
}
具体数据库数据(数据库内容过于简单,真实案例比这复杂仅供参考)
gitee仓库分享
gitee仓库地址:WWangs/aop实现权限