手记

实战课程->电商后台->动态代理实现权限拦截

package com.mmall.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
public class AuthorityProxy implements InvocationHandler {
    private Object target;
    private Object obj;
    private IUserService iUserService;
    public AuthorityProxy(Object obj, IUserService iUserService) {
        this.obj = obj;
        this.iUserService = iUserService;
    }
    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        if (obj instanceof User) {
            if (iUserService.checkAdminRole((User) obj).isSuccess()) {
                return method.invoke(target, args);
            }
            return ServerResponse.createByErrorMessage("无权限操作");
        }
        return ServerResponse.createByErrorCodeMessage(
                ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
    }
}
0人推荐
随时随地看视频
慕课网APP