SSH实现一个简单的权限控制实例(二)
博客专区 > 丶KKdo 的博客 > 博客详情
SSH实现一个简单的权限控制实例(二)
丶KKdo 发表于1年前
SSH实现一个简单的权限控制实例(二)
  • 发表于 1年前
  • 阅读 10
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

接上文,基本配置已经配置好,那么编写控制用户登录的Action.

/*UserAction.java*/
@Component @Scope("prototype")
public class UserAction extends ActionSupport {
	public String loginname;
	public String password;
	private String checkcode;

	public String getCheckcode() {
		return checkcode;
	}

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	public String getLoginname() {
		return loginname;
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Resource
	private UserService userService;
	
	@Resource
	private MenuService menuService;

	@SuppressWarnings({ "unchecked", "unused" })
	@Transactional
	public String login() {
		String code = (String) ServletActionContext.getRequest().getSession().getAttribute("checkcode");
	    if((code.toUpperCase()).equals((checkcode.toUpperCase()))) {
			List<User> list = userService.login(loginname, password);
			if(list == null || list.size() == 0) {
				this.addActionError("用户名或密码错误!");
				return ERROR;
			}
			User user = list.get(0);
			user.setLastLogin(DateFormat.dateFormat(new Date()));
			userService.update(user);
			ServletActionContext.getRequest().getSession().setAttribute("user", user);
			List<Menu> menuList =  (List<Menu>) ServletActionContext.getRequest().getSession().getAttribute("menuList");
			if(menuList == null) {
				menuList = menuService.getNeed(0);
				ServletActionContext.getRequest().getSession().setAttribute("menuList", menuList);
			}
		}else {
			this.addActionError("验证码错误!");
			return ERROR;
		}
		return "loginSuccess";
	}
	
	public String execute() {
		return SUCCESS;
	}
	
	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return LOGIN;
	}
}

将登录成功之后的用户信息和菜单存放到session中,配置struts中对应的方法:

<!-- struts.xml -->
<action name="user_*" class="userAction" method="{1}">
	<result name="login">/jsp/login.jsp</result>
	<result name="loginSuccess" type="redirect">/jsp/index.jsp</result>
	<result name="input">/jsp/login.jsp</result>
</action>

编写在Action中出现的获取菜单和用户信息的方法,所需要的实体类现在只有简单pojo,就不给出了,service层的代码就是一个简单调用Dao层的方法,下面直接给Dao层的方法:

/* UserDao.java */

public class UserDao extends HibernateDaoSupport{
	
	@SuppressWarnings("unchecked")
	public List<User> login(String loginname, String password) {
		String hql = "from User U where U.loginname = ? and U.password = ?";
		List<User> list = this.getHibernateTemplate().find(hql, 
				new Object[] {loginname, password});
		return list;
	}
	
	public void update(User user) {
		this.getHibernateTemplate().update(user);
	}
/* MenuDao.java */
public class MenuDao extends HibernateDaoSupport {

	@SuppressWarnings("unchecked")
	public List<Menu> getAll() {
		String hql = "from Menu";
		return this.getHibernateTemplate().find(hql);
	}
	
	@SuppressWarnings("unchecked")
	public List<Menu> getSubMenu(Menu menu) {
		String hql = "from Menu M where M.parentId = ?";
		Integer id = menu.getMenuId();
		List<Menu> list =  this.getHibernateTemplate().find(hql,
				new Object[] {id});
		for(Menu child : list) {
			child.setHasMenu(true);
		}
		return list;
	}
	
	public List<Menu> getNeed(int index) {
		List<Menu> menus = this.getAll();
		List<Menu> parent = new ArrayList<Menu>();
		List<Menu> child = new ArrayList<Menu>();
		for(Menu menu : menus) {
			if(menu.getParentId() == null) {
				menu.setHasMenu(true);
				menu.setSubMenu(this.getSubMenu(menu));
				parent.add(menu);
			} else {
				child.add(menu);
			}
		}
		switch(index) {
		case 0 :
			//获取父菜单
			return parent;
		case 1 :
			//获取子菜单
			return child;
		}
		return null;
	}
} 

Menu.java有一个属性是hasMenu,用来前台做是否显示使用.

然后,前台页面index.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>测试系统</title>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.5.1.min.js"></script>
</head>
<body>
	<% request.setCharacterEncoding("utf-8"); %>
	<div class="main_header">
		<div class="header_left"></div>
		<div class="header_right">
			<span id="sysTime"></span>
			<span>${user.username },您好!</span>
			<a href="javascript:logout();"><img src="${pageContext.request.contextPath}/images/out.gif" border="0"/></a>
		</div>
	</div>
	<div class="main_content">
		<div class="content_left">
			<c:forEach items="${menuList}" var="menu">
			<!-- 判断是否有权限 -->
				<c:if test="${menu.hasMenu}">
				<h1><a>${menu.menuName }</a></h1>
				<div class="menu_line">
					<ul>
					<c:forEach items="${menu.subMenu}" var="sub">
					<!-- 子菜单的权限判断 -->
						<c:if test="${sub.hasMenu}">
						<c:choose>
							<c:when test="${not empty sub.menuUrl}">
							<!-- url是否为空 -->
							<li><a href="${sub.menuUrl }" target="mainFrame">${sub.menuName }</a></li>
							</c:when>
							<c:otherwise>
							<!-- 如果为空直接改变tab的名字 -->
							<li><a href="javascript:void(0);" target="mainFrame">${sub.menuName }</a></li>
							</c:otherwise>
						</c:choose>
						</c:if>
					</c:forEach>
					</ul>
				</div>
				</c:if>
			</c:forEach>
		</div>
		<div class="content_center">&nbsp;</div>
		<div class="content_right">
			<table cellspacing="0" cellpadding="0">
				<tr style="height:29px;background: url('${pageContext.request.contextPath}/images/content-bg.gif') repeat-x;">
					<td style="height:29px;width:17px;background: url('${pageContext.request.contextPath}/images/left-top-right.gif') no-repeat;"></td>
					<td style="height:29px;line-height:29px;"><div class="content_title">首页</div></td>
					<td style="height:29px;width:16px;background: url('${pageContext.request.contextPath}/images/nav-right-bg.gif') no-repeat;"></td>
				</tr>
				<tr>
					<td style="background:url('${pageContext.request.contextPath}/images/mail_leftbg.gif') repeat-y;"></td>
					<td style="background-color:#FAFBFD;">
						<iframe name="mainFrame" id="mainFrame" frameborder="0" src="${pageContext.request.contextPath}/jsp/default.jsp" style="width:100%;height:100%;"></iframe>
					</td>
					<td style="background:url('${pageContext.request.contextPath}/images/mail_rightbg.gif') repeat-y;"></td>
				</tr>
				<tr style="background: url('${pageContext.request.contextPath}/images/buttom_bgs.gif') repeat-x;">
					<td style="height:17px;background: url('${pageContext.request.contextPath}/images/buttom_left2.gif') no-repeat;"></td>
					<td></td>
					<td style="height:17px;background: url('${pageContext.request.contextPath}/images/buttom_right2.gif') no-repeat;"></td>
				</tr>
			</table>
			<div class="sys_bottom"> Copyright &copy; 2011 XXX管理系统</div>
		</div>
	</div>
	
<script type="text/javascript">
$(document).ready(function(){
	getTime();
	window.setInterval(getTime, 1000);
	$("h1 a").bind("click",function(){
		var obj = $(this).parent().next();
		obj.slideToggle("fast","linear");
		//obj.fadeToggle("fast","linear");
	});
	$(".menu_line a").bind("click",function(){
		$(".content_title").html($(this).html());
		//$("#mainFrame").attr("src","");
		$(".menu_line a").css("background-image","url('${pageContext.request.contextPath}/images/menu_bg1.gif')");
		$(".menu_line a").css("color","#333333");
		$(".menu_line a").css("font-weight","normal");
		$(".menu_line a").bind({
			mouseover:function(){
				$(this).css("background-image","url('${pageContext.request.contextPath}/images/menu_bg2.gif')");
				$(this).css("color","#006600");
				$(this).css("font-weight","bold");
			},
			mouseout:function(){
				$(this).css("background-image","url('${pageContext.request.contextPath}/images/menu_bg1.gif')");
				$(this).css("color","#333333");
				$(this).css("font-weight","normal");
			}
		})
		$(this).css("background-image","url('${pageContext.request.contextPath}/images/menu_bg2.gif')");
		$(this).css("color","#006600");
		$(this).css("font-weight","bold");
		$(this).unbind("mouseout");
	});
	initRightContentHeightAndWidth();
});

function initRightContentHeightAndWidth(){
	var height = $(window).height()<$(document).height()?$(window).height():$(document).height();
	var width = $(window).width()<$(document).width()?$(window).width():$(document).width();
	$(".content_right table").width(width-$(".content_left").width()-$(".content_center").width());
	$(".content_right table tr:eq(1) td").height(height-$(".main_header").height()-$(".sys_bottom").height()-46);
}

function getTime(){
	var date = new Date();
	var y = date.getFullYear();
	var m = date.getMonth()+1;
	var d = date.getDate();
	var h = date.getHours();
	var i = date.getMinutes();
	var s = date.getSeconds();
	$("#sysTime").html(y+"年"+(m>9?m:("0"+m))+"月"+(d>9?d:("0"+d))+"日 "+(h>9?h:("0"+h))+":"+(i>9?i:("0"+i))+":"+(s>9?s:("0"+s)));
}

function logout(){
	if(confirm("确定要退出吗?")){
		document.location = "user_logout.html";
	}
}
</script>
</body>
</html>

自定义一个Inteceptor来拦截未登录的用户:

@Component
public class AuthInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		User user = (User) ServletActionContext.getRequest().
				getSession().getAttribute("user");
		if(user != null) {
			String result = invocation.invoke();
			return result;
		}
		return "error";
	}

}

在struts中配置自定义拦截器:

		<interceptors>
			<interceptor name="authInterceptor" class="authInterceptor"></interceptor>
			<interceptor-stack name="myStack">
				<interceptor-ref name="defaultStack"></interceptor-ref>
				<interceptor-ref name="authInterceptor"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
	
		<action name="user_*" class="userAction" method="{1}">
			<result name="error">/jsp/login.jsp</result>
			<result name="login"  type="redirect">/auth/auth.html</result>
			<result name="loginSuccess" type="redirect">/auth/auth.html</result>
			<result name="input">/jsp/login.jsp</result>
		</action>
		
		<action name="index" class="indexAction">
			<result>/jsp/login.jsp</result>
		</action>
		
		<action name="auth" class="authAction" method="authCheck">
			<result>/jsp/index.jsp</result>
			<result name="error" type="redirect">/auth/index.html</result>
			<interceptor-ref name="myStack"></interceptor-ref>
		</action>

将之前的也修改一下,改成重定向模式.

然后访问auth.html如果未登录会跳转到登录界面,然后登录:

这些已经是自己再数据库中插入了一些测试数据,显示成功.

共有 人打赏支持
粉丝 2
博文 22
码字总数 13683
×
丶KKdo
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: