Aspecj实现的AOP,AOP实现的登录校验

①需要导入的jar包



org.springframework
spring-aop
${spring.version}


org.springframework
spring-aspects
${spring.version}




aopalliance
aopalliance
1.0


org.aspectj
aspectjweaver
1.8.10



cglib
cglib
2.2

②需要配置的XML文件(需将切面类注入到spring容器中)






③编写切面类

@Component
@Aspect
public class UserAop {
@Pointcut("execution(public * njupt.test.ssm.controller.StudentController.*(..))")
public void pointCut(){}

@Before("pointCut()")
public void testCheck(){
System.out.println("1");
}

@Around("pointCut()")
public void checkRoleAop(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("方法执行前");
joinPoint.proceed();
System.out.println("方法执行后");

}

}

Aspecj实现的AOP,AOP实现的登录校验_第1张图片

AOP实现的登录校验

 

1.首先需要在登录的时候设置session,将用户信息写入session

controller层:

@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;

@RequestMapping(value = "/loginCheck",method = RequestMethod.GET)
@ResponseBody
public ServerResponse loginCheck(HttpSession session, @RequestParam("userId") String userId,
@RequestParam("userPassword")String userPassword){
ServerResponse serverResponse = userService.loginCheck(userId,userPassword);
if (serverResponse.checkIsSuccess()){
//设置session
session.setAttribute("user",serverResponse.getData());
return serverResponse;
}
return ServerResponse.createByError("账号或密码错误!");
}
}

2.调用功能时,校验用户是否登录,登录权限(以管理员为例)写一个切面类

@Component
@Aspect
public class UserAop {
@Pointcut("execution(public * njupt.test.ssm.controller.StudentController.*(..))")
public void pointCut(){}


@Around("pointCut()")
public ServerResponse checkRoleAop(ProceedingJoinPoint joinPoint) throws Throwable {
//获取请求域
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取session中的信息
User user = (User) request.getSession().getAttribute("user");
if (user == null){
return ServerResponse.createByNeedLogin();
}
if (user.getUserRole()!=1){
return ServerResponse.createByError("非管理员,无此权限!");
}
return (ServerResponse) joinPoint.proceed();
}

}

附:获取被代理类信息的方法

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}", request.getRequestURL());
//method
logger.info("method={}", request.getMethod());
//ip
logger.info("ip={}", request.getRemoteAddr());
//类方法
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//参数
logger.info("args={}", joinPoint.getArgs());

 

你可能感兴趣的:(SSM)