Springmvc 使用Aspect 使用权限注解拦截

本文介绍了如何使用Spring AOP和自定义注解实现权限拦截功能。首先定义了`@Permission`注解用于标记需要权限校验的方法,接着创建了`PermissionAspect`切面类进行权限校验,包括角色权限的验证和业务逻辑的执行。在XML配置中启用了AspectJ注解支持,并在登录入口和登录认证方法中展示了注解的使用。整个流程确保了只有具备相应权限的用户才能访问特定业务功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、权限注解类


import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 系统权限拦截注解
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission {
	
	/**
     * 权限模块 
     */
    public String title() default "";
    
    /**
     * 权限路径
     * */
    public String url() default "";
    
    /**
     * 权限描述
     * @return
     */
    String description() default "";

}

2、权限拦截实现

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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 com.common.annotation.Permission;
import com.core.exception.BaseRuntimeException;
import com.core.exception.user.AccountNotFoundException;
import com.core.exception.user.UnauthorizedException;
import com.core.web.CmsUtils;
import com.core.web.ServletUtils;
import com.coupon.entity.MerchantUser;
import com.coupon.service.PermissionService;

/**
 *  权限拦截校验
 *	@Aspect:作用是把当前类标识为一个切面供容器读取
 *	@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
 *	@Around:环绕增强,相当于MethodInterceptor
 *	@AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
 *	@Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
 *	@AfterThrowing:异常抛出增强,相当于ThrowsAdvice
 *	@After: final增强,不管是抛出异常或者正常退出都会执行
 */
@Aspect
@Component
public class PermissionAspect {
	
	private static final Logger log = LoggerFactory.getLogger(PermissionAspect.class);
    
    @Autowired
    private PermissionService permissionService;
    
	//日志切入点
	@Pointcut("@annotation(com.common.annotation.Permission)")
	public void logPointCut() {
		
	}
	
	
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		 log.info("==========进入业务权限校验============================");
		//1.记录日志信息
        Signature signature = joinPoint.getSignature();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = signature.getName();
        log.info("className:{},methodName:{}",className,methodName);
        //2.角色权限校验
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        if(targetMethod.isAnnotationPresent(Permission.class)){
        	Permission permission = targetMethod.getAnnotation(Permission.class);
            HttpServletRequest request = ServletUtils.getRequest();
            //验证是否有权限
            String url = permission.url();
            MerchantUser merchantUser = CmsUtils.getMerchantUser(request);
            if(merchantUser==null) {
            	throw new AccountNotFoundException("用户不存在");
            }
            if(!permissionService.isHaveOperationAuthority(merchantUser, url)) {
            	//抛出权限异常
            	throw new UnauthorizedException("用户没有权限");
            }else {
            	//3.执行业务逻辑,放行
                return joinPoint.proceed();
            }
        }
        throw new BaseRuntimeException("未配置业务权限校验");
	}

}

3、xml配置

    <!-- aop 权限拦截 -->
  	<bean id="permissionAspect" class="com.aspect.PermissionAspect"/>

    <!-- 启动对@AspectJ注解的支持  --> 
   	<aop:aspectj-autoproxy proxy-target-class="true" /> 

4、注解使用

@Permission(title="用户模块",url="/user/v_list.do")
	@RequestMapping("/v_list.do")
	public String list(HttpServletRequest request, ModelMap model, Integer pageNo, Integer pageSize, String userName,
			Integer state, String realName, String mobile, Integer isSuper, Integer type) {
        //业务代码
		return "/merchant_tpl/user/list";
	}

登录入口

@RequestMapping(value = "/login.do", method = RequestMethod.POST)
    @ResponseBody
	public ApiResult login(HttpServletRequest request, HttpServletResponse response, String userName, String password,
			String captcha, HttpSession httpSession) {
		JSONObject data = new JSONObject();
		String msg = "";
		if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
			msg = "用户名、密码未填写";
			return ApiResultUtil.tips(msg);
		} else {
			try {
				//完成用户认证,日志记录、授权业务
				MerchantUser merchantUser = userAuthService.doAuthentication(request, response, userName, password);
				if (merchantUser != null) {
					// 跳转到首页
					data.put("redirectUrl", "/store/index.do");
					return ApiResultUtil.success(data);
				}
			} catch (LockedException e) {
				System.out.println(e.getMessage());
				return ApiResultUtil.tips(e.getMessage());
			} catch (UsernameNotFoundException e) {
				System.out.println(e.getMessage());
				return ApiResultUtil.tips("用户名或密码错误");
			} catch (DisabledException e) {
				System.out.println(e.getMessage());
				return ApiResultUtil.tips(e.getMessage());
			} catch (IncorrectCredentialsException e) {
				System.out.println(e.getMessage());
				return ApiResultUtil.tips(e.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				return ApiResultUtil.error();
			}
			return ApiResultUtil.error();
		}
	}

登录认证

jar 依赖

aspectjrt-1.9.6.jar
aspectjweaver-1.8.9.jar
spring-aspects-4.3.18.RELEASE.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值