spring 通过注解 做权限控制

注解这样写,我用的是数组的形式可以传多个

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 ULifePermission {
    String[] value() default {};
}

实例接口如下

@ULifePermission({"2100","2101","2012","2103","2104","2015","2106","2107"})
    @RequestMapping("/page/{v}")
    @ResponseBody
    public ResultBean searchCompany(
                    @RequestParam(required = false) String name,
                    @RequestParam(required = false) String adcode,
                    @RequestParam(defaultValue="1") Integer pageIndex,
                    @RequestParam(defaultValue="20") Integer pageSize,
                    @RequestParam(required = true) String safetyId,
                    @RequestParam(required = true) String addRoleId,
                    @RequestParam(required = false) String addCompId,
                    @RequestParam(required = false) String addStoreId) {
        try {
            PageBean<SysCompanyLMvo> companys = companyService.searchCompany(name, adcode, pageIndex, pageSize, addRoleId, addCompId, addStoreId);
            
            return ResultUtil.returnResult(companys, "查询企业成功");
        }  catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.returnResult(e);
        }
    }

过滤器如下

public class MainFilter extends HandlerInterceptorAdapter {
    private static Logger log = LoggerFactory.getLogger(MainFilter.class);

     @Resource(name = "commonService")
     private ICommonService commonService;
    
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        ULifePermission permissionAnnotation = ((HandlerMethod) handler).getMethod().getDeclaredAnnotation(ULifePermission.class);
        String[] permission = permissionAnnotation == null ? null : permissionAnnotation.value();
        log.debug(path + "(" + StringUtils.join(permission, "|") + ")");
        
        try {
            commonService.checkUser(request, permission);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(ResultUtil.returnJson(e));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        return true;
    }

}

permission就是注解中的id传,然后取request中session中的sid串做对比就行了(本人没用session用的redis)

checkUser部分代码

@Override
    public void checkUser(HttpServletRequest request, String[] permissions) {
        String token = request.getParameter("token");
        
        if (StringUtils.isEmpty(token) || RedisUtil.get(token, "addId") == null) {
            throw new SifudeException(SifudeExceptionEnum.USER_UNLOG_EXCEPTION);
        }
        
        String sids = RedisUtil.get(token, "sids") + "";

        if (permissions != null) {
            boolean flag = false;
            for (String permission : permissions) {
                if (sids.contains(permission)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw new SifudeException(SifudeExceptionEnum.USER_PERMISSON_ILLEGAL_EXCEPTION);
            }
        }
    }

这样就完成了,最后是spring中对过滤器的配置

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/comp/**" />
            <bean class="com.sifude.youlife.filter.MainFilter" />
        </mvc:interceptor>
    </mvc:interceptors>

恩恩,就是这样,有什么不明白的地方欢迎留言讨论

你可能感兴趣的:(redis,注解,spring,权限,过滤器,登录验证)