1、前言
实验内容:利用Spring技术实现校友信息网站。要求采用MVC框架,同时要求加入面向切面的编程。
构建一个用户记录的切面。要求:
a. 对于所有的登录操作,记录各各次登录的时间、用户,存入UserLog表格中。
b. 对于所有的登出操作,记录各各次登录的时间、用户,存入UserLog表格中。
c. 对于用户新的输入操作,记录其表单值,存入InsertLog表格中。
2、实验环境
- 操作系统:Windows 10
- 实验工具:IntelliJ IDEA & vue
- 数据库:Mysql
- 环境:Java jdk 1.8
3、实验过程
3.1 构建数据库
构建管理员信息表
构建用户登入登出信息表,其中operation为用户操作,1表示用户登陆系统,0表示用户登出系统。
构建校友信息表,包括姓名和手机号信息
构建插入日志记录表格,表格中记录了执行插入操作的id和时间
3.2 项目后端编码
后端代码结构
AdminController类代码
UserController类编码
AdminService类编码
UserService类编码
UserlogService类编码
InsertlogService类编码
3.3 AOP
package com.example.aopTest.AOP;
import com.example.aopTest.Entity.AdminEntity;
import com.example.aopTest.Entity.UserEntity;
import com.example.aopTest.Service.InsertlogService;
import com.example.aopTest.Service.UserlogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SpringAopTest {
@Autowired
private UserlogService userlogService;
@Autowired
private InsertlogService insertlogService;
//登入切点
@Pointcut(value = "execution(* com.example.aopTest.Controller.AdminController.login(*))")
public void loginAOP(){
}
//登出切点
@Pointcut(value = "execution(* com.example.aopTest.Controller.AdminController.logout(*))")
public void logoutAOP(){
}
//插入信息切点
@Pointcut(value = "execution(* com.example.aopTest.Controller.UserController.createUser(*))")
public void insertAOP(){
}
//将登陆信息写入数据库
@Before("loginAOP()")
public void beforelogin(JoinPoint joinPoint){
AdminEntity adminEntity =(AdminEntity) joinPoint.getArgs()[0];
userlogService.login(adminEntity.getUsername());
}
//将登出信息写入数据库
@Before("logoutAOP()")
public void beforelogout(JoinPoint joinPoint){
String username=String.valueOf(joinPoint.getArgs()[0]);
userlogService.logout(username);
}
//将插入信息写入数据库
@Before("insertAOP()")
public void beforeinsert(JoinPoint joinPoint){
UserEntity userEntity =(UserEntity)joinPoint.getArgs()[0];
insertlogService.insert(userEntity.getId());
}
}
3.4 前端代码
3.5 运行结果
登录前
登录后页面
登录日志中新增一条记录
登录后数据库,新增一条登录信息
新建用户
新建用户成功
数据库中成功增加一个用户
插入记录中新增一条记录
插入日志新增一条记录
退出登录后新增一条退出登录记录
4、总结
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。