Java实现在控制层设置用户访问权限

服务器可能会收到各种角色用户的请求,如普通用户、游客、会员等。有些服务器接口,我们不想对所有角色开放,我们可以在接口里面设置访问权限,拒绝掉没有权限的请求。本文将介绍如何设置接口的角色访问权限,包括:“根据用户类型定义用户域枚举类”、“定义在服务器接口的拦截方法canCallCurrentAction”、“在Action接口调用canCallCurrentAction”。

1、根据用户类型定义用户域枚举类。

	/* 用户域。用于在Action层进行权限控制 */
	public enum EnumUserScope {
		STAFF("STAFF", 1), //
		BXSTAFF("BXSTAFF", 2), //
		VIP("VIP", 4), //
		POS("Pos", 8), //
		ANYONE("ANYONE", 16); // 任何人都能访问当前Action

		private String name;
		private int index;

		private EnumUserScope(String name, int index) {
			this.name = name;
			this.index = index;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public static String getName(int index) {
			for (EnumEnv e : EnumEnv.values()) {
				if (e.getIndex() == index) {
					return e.name;
				}
			}
			return null;
		}
	}

2、定义在服务器接口的拦截方法canCallCurrentAction。

	/**
	 * @param whoCanCallCurrentAction
	 *            必须提供的会话的组合
	 * @return true,当前会话中有目标会话,有权限访问当前action;false,当前会话中没有目标会话,无权限访问当前action
	 */
	protected boolean canCallCurrentAction(HttpSession session, int whoCanCallCurrentAction) {
		do {
			if ((whoCanCallCurrentAction & EnumUserScope.ANYONE.getIndex()) == EnumUserScope.ANYONE.getIndex()) {
				return true;
			}
			if ((whoCanCallCurrentAction & EnumUserScope.STAFF.getIndex()) == EnumUserScope.STAFF.getIndex()) {
				if (session.getAttribute(EnumSession.SESSION_Staff.getName()) != null) {
					return true;
				}
			}
			if ((whoCanCallCurrentAction & EnumUserScope.BXSTAFF.getIndex()) == EnumUserScope.BXSTAFF.getIndex()) {
				if (session.getAttribute(EnumSession.SESSION_BxStaff.getName()) != null) {
					return true;
				}
			}
			if ((whoCanCallCurrentAction & EnumUserScope.VIP.getIndex()) == EnumUserScope.VIP.getIndex()) {
				if (session.getAttribute(EnumSession.SESSION_Vip.getName()) != null) {
					return true;
				}
			}
			if ((whoCanCallCurrentAction & EnumUserScope.POS.getIndex()) == EnumUserScope.POS.getIndex()) {
				if (session.getAttribute(EnumSession.SESSION_POS.getName()) != null) {
					return true;
				}
			}
		} while (false);
		return false;
	}

用户域枚举类的角色STAFF、BXSTAFF、VIP、POS和ANYNONE的名称值为1、2、4、8、16,二进制表示为1、10、100、1000、10000。

在canCallCurrentAction方法参数里传入了角色类型的参数whoCanCallCurrentAction,只有canCallCurrentAction与用户域名称值相同时,它们的与操作才会为true,允许此次请求。

3、在Action接口调用canCallCurrentAction 。

		if (!canCallCurrentAction(session, BaseAction.EnumUserScope.STAFF.getIndex())) {
			logger.debug("无权访问本Action");
			return null;
		}

 

posted @ 2021-12-22 16:43  Boxin-kim  阅读(387)  评论(0编辑  收藏  举报
Web Analytics
Guang Zhou Boxin