Spring Boo使用AOP做权限控制

一.需求

在访问某些方法之前做一些事情,比如判断该用户是否加入该课程。

二.实现

1.定义一个注解,这样在某个方法上面加上该注解就触发AOP

package com.ruoyi.framework.aspectj.lang.annotation;

import java.lang.annotation.*;

/**
 * 检验该学生是否在该课程
 * 
 * @author wangcy
 *
 */
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserHasCourse
{
}

2.定义AOP的切面类

package com.ruoyi.framework.aspectj;

import com.ruoyi.common.exception.course.UserNotCourseException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.aspectj.lang.annotation.UserHasCourse;
import com.ruoyi.project.my.course.service.ICourseUserService;
import com.ruoyi.project.my.course.vo.CourseUserVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

import static com.ruoyi.common.utils.security.ShiroUtils.getUserId;

/**
 * 判断该用户是否加入了该课程
 * 
 * @author wangcy
 */
@Aspect
@Component
public class UserNotCourseAspect
{

    @Autowired
    private ICourseUserService userService;

    private static final Logger log = LoggerFactory.getLogger(UserNotCourseAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.ruoyi.framework.aspectj.lang.annotation.UserHasCourse)")
    public void CoursePointCut()
    {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @Before("CoursePointCut()")
    public void doBefore(JoinPoint  joinPoint) throws Throwable
    {
        //若是管理员 直接放
//        if(getUserId() == 1L){
//            return;
//        }
        // 获得注解
        UserHasCourse controllerCourse = getAnnotationLog(joinPoint);
        if (controllerCourse == null)
        {
            return;
        }
        //获取占位符上面的课程ID  #{courseID}
        HttpServletRequest request = ServletUtils.getRequest();
        String requestURI = request.getRequestURI();
        Long courseID = Long.parseLong(requestURI.substring(requestURI.lastIndexOf("/")+1));

        //判断该用户是否在该课程
        CourseUserVo courseUserVo = new CourseUserVo();
        courseUserVo.setCourseId(courseID);
        List<CourseUserVo> courseUserVos = userService.selectCourseUserVoListByCourseId(courseUserVo);
        Boolean flag=false;
        for(CourseUserVo user:courseUserVos){
            if(user.getUserId() == getUserId()){
                flag=true;
                break;
            }
        }
        if(!flag){//没有权限
            throw new UserNotCourseException("抱歉,该用户未在该课程");
        }
    }



    /**
     * 是否存在注解,如果存在就获取
     */
    private UserHasCourse getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(UserHasCourse.class);
        }
        return null;
    }
}

3.定义一个处理异常的类

@RestControllerAdvice
public class GlobalExceptionHandler
{
    /**
     * 用户未在该课程
     */
    @ExceptionHandler(UserNotCourseException.class)
    public Object userNotCourseException(HttpServletRequest request,UserNotCourseException e)
    {
        log.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request))
        {
            return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
        }
        else
        {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error/unhasCourse");
            return modelAndView;
        }
    }
    }

4.使用

    @GetMapping("/courseDetails/{courseID}")
    @UserHasCourse  //该用户是否在该课程
    public String toCourseDetails(@PathVariable("courseID") Long courseID, ModelMap modelMap){
        Course course = iCourseService.selectCourseById(courseID);
        modelMap.addAttribute("course",course);
        return "web/courseDetails";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值