思路
划分权限的思路大概如下:
然后在注册的时候要考虑注册的是管理员账号还是普通会员的账号,然后我这里呢是:如果要注册管理员账号,需要填写一个邀请码,如果普通会员就可以不用填写,如果你们有更好的方法也可以。
界面
首先,样式我在上一篇博客里已经调好了,感兴趣的阔以去康康
文章链接
具体实现
jsp页面
先看jsp页面代码:
登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登录界面</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/css/bootstrap.min.css" >
<script src="${pageContext.request.contextPath }/static/js/bootstrap.min.js" ></script>
<style>
.form-signin{
width: 300px;
position: relative;
top:100px;
left: 50%;
margin-left: -200px;
}
</style>
</head>
<body >
<form class="form-signin" action="${pageContext.request.contextPath }/user.action?methodName=login" method="post">
<h1 class="h3 mb-3 font-weight-normal text-center">登录</h1>
<br/>
<input type="text" id="uname" name="name" class="form-control" placeholder="用户名" required autofocus>
<br/>
<input type="password" id="pwd" name="pwd" class="form-control" placeholder="密码" required>
<input type="checkbox" value="remember-me"> Remember me
<br/><br/>
<button class="btn btn-lg btn-info btn-block" id="login" type="submit">登录</button>
<p class="mt-5 mb-3 text-muted">© 2017-2020</p>
</form>
</body>
</html>
注册页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>注册界面</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/css/bootstrap.min.css" >
<script src="${pageContext.request.contextPath }/static/js/bootstrap.min.js" ></script>
<style>
.form-signin{
width: 300px;
position: relative;
top:100px;
left: 50%;
margin-left: -200px;
}
</style>
</head>
<body >
<form class="form-signin" action="${pageContext.request.contextPath }/user.action?methodName=add" method="post">
<h1 class="h3 mb-3 font-weight-normal text-center">注册</h1>
<br/>
<input type="text" id="name" name="name" class="form-control" placeholder="用户名" required autofocus>
<br/>
<input type="password" id="pwd" name="pwd" class="form-control" placeholder="密码" required>
<br/>
<input type="text" id="yzm" name="yzm" class="form-control" placeholder="如果要注冊管理員账号,请填写邀请码" required>
<input type="checkbox" value="remember-me"> Remember me
<br/><br/>
<button class="btn btn-lg btn-info btn-block" type="submit">注册</button>
<p class="mt-5 mb-3 text-muted">© 2017-2020</p>
</form>
</body>
</html>
mvc.xml配置
这里定义跳转页面,比较方便,不会乱
<config>
<action path="/user" type="com.wangjuanxia.web.UserAction">
<forward name="index" path="/index.jsp" redirect="false" />
<forward name="login" path="/login.jsp" redirect="false" />
<forward name="register" path="/register.jsp" redirect="false" />
</action>
</config>
web层 action
处理业务逻辑,登录和增加用户(注册)方法
package com.wangjuanxia.web;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wangjuanxia.dao.UserDao;
import com.wangjuanxia.entity.user;
import com.wangjuanxia.framemark.ActionSupport;
import com.wangjuanxia.framemark.ModelDriver;
import com.wangjuanxia.util.StringUtils;
public class UserAction extends ActionSupport implements ModelDriver<user>{
private user u=new user();
private UserDao ud=new UserDao();
@Override
public user getModel() {
// TODO Auto-generated method stub
return u;
}
public String login(HttpServletRequest req,HttpServletResponse resp) {
try {
user user=null;
if(!"null".equals(u.getName())&&!"null".equals(u.getPwd())) {
try {
user = this.ud.login(u, null).get(0);
} catch (IndexOutOfBoundsException e) {
return "login";
}
if(user!=null) {
req.getSession().setAttribute("user", user);
return "index";
}
}
} catch (InstantiationException e) {
e.printStackTrace();
return "login";
} catch (IllegalAccessException e) {
e.printStackTrace();
return "login";
} catch (SQLException e) {
e.printStackTrace();
return "login";
} catch (ParseException e) {
e.printStackTrace();
return "login";
}
return "login";
}
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
String yzm=req.getParameter("yzm");
// u.setId(5);
u.setType(2);
if("solar".equals(yzm)) {
u.setType(1);
}
int add = this.ud.add(u);
if(add!=0) {
return "login";
}
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "register";
}
}
dao方法
增加用户和登录的方法,sql语句
id设置了自增长,所以sql语句里放null就行。
package com.wangjuanxia.dao;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import com.wangjuanxia.entity.user;
import com.wangjuanxia.util.BaseDao;
import com.wangjuanxia.util.PageBean;
import com.wangjuanxia.util.StringUtils;
public class UserDao extends BaseDao<user> {
public List<user> login(user u,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException, ParseException{
String sql="select * from t_easyui_user where true";
String name=u.getName();
String pwd=u.getPwd();
if(StringUtils.isNotBlank(name)&&StringUtils.isNotBlank(pwd)) {
sql+=" and name='"+name+"' and pwd='"+pwd+"'";
}
System.out.println(sql);
return super.executeQuery(sql, user.class, pageBean);
}
public int add(user u) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="insert into t_easyui_user values(null,?,?,?)";
return super.executeUpdate(sql, u, new String[] {"name","pwd","type"});
}
}
权限表的显示
jsp页面
使用js文件配合easyui组件显示树形菜单权限
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主界面</title>
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<!-- 定义图标的样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/icon.css">
<!--组件库源文件的js文件 -->
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/index.js"></script>
</head>
<input type="hidden" id="ctx" value="${pageContext.request.contextPath }"/>
<body class="easyui-layout">
<div data-options="region:'north',border:false" style="height:60px;background:#B3DFDA;padding:10px">这里可以放logo</div>
<div data-options="region:'west',split:true,title:'目录'" style="width:150px;padding:10px;">
<ul id="tt"></ul>
</div>
<div data-options="region:'east',split:true,collapsed:true,title:'右边'" style="width:100px;padding:10px;">右边</div>
<div data-options="region:'south',border:false" style="height:50px;background:#A9FACD;padding:10px;">这里放版权信息</div>
<div data-options="region:'center',title:'内容'">
<div id="tab" class="easyui-tabs" style="width:100%;height:100%;">
<div title="首页" style="padding:20px;display:none;">
一般首页放本站的各种数据指标,各个模块的使用情况,数据量,报表。
${user.name },${user.pwd }
</div>
<div id="rcmenu" class="easyui-menu">
<div id="closecur">
关闭当前
</div>
<div id="closeall">
关闭全部
</div>
<div id="closeother">
关闭其他
</div>
<div class="menu-sep"></div>
</div>
</div>
</div>
</body>
</html>
js文件
主要用到的组件是tree
具体的使用我之前也写过博客,可以参考
文章链接
$(function(){
var ctx=$("#ctx").val();
var ctx=ctx+'/';
$('#tt').tree({
url:ctx + 'permission.action?methodName=menuTree',
onClick: function(node){//当用户点击时执行
//目前问题:相同的tab页反复打开
//判断是否存在相同的选项卡,如果存在就切换到对应的选项卡,如果不存在就打开一个
if($('#tab').tabs('exists',node.text)){
//存在,切换选项卡
$('#tab').tabs('select',node.text);
}else{
//不存在,新增选项卡
//存在问题,非叶子节点(当url为空)按开发角度来说是不能打开页面的
var url=node.attributes.self.url;
if(url){
var content='<iframe scrolling="no" frameborder="0" src="'+ctx+url+'" width="99%" height="99%"></iframe>';
$('#tab').tabs('add',{
title:node.text,
content: content,
closable:true,
tools:[{
iconCls:'icon-mini-refresh',
handler:function(){
alert('refresh');
}
}]
});
}
}
}
});
$(".tabs-header").bind('contextmenu',function(e){
e.preventDefault();
$('#rcmenu').menu('show', {
left: e.pageX,
top: e.pageY
});
});
//关闭当前标签页
$("#closecur").bind("click",function(){
var tab = $('#tab').tabs('getSelected');
var index = $('#tab').tabs('getTabIndex',tab);
$('#tab').tabs('close',index);
});
//关闭所有标签页
$("#closeall").bind("click",function(){
var tablist = $('#tab').tabs('tabs');
//下标小于0,不删除第一个,小于等于0就全部删除
for(var i=tablist.length-1;i>0;i--){
$('#tab').tabs('close',i);
}
});
//关闭非当前标签页
$("#closeother").bind("click",function(){
var tablist = $('#tab').tabs('tabs');
var tab = $('#tab').tabs('getSelected');
var index = $('#tab').tabs('getTabIndex',tab);
for(var i=tablist.length-1;i>index;i--){
$('#tab').tabs('close',i);
}
var num = index-1;
//下标小于0,不删除第一个,小于等于0就全部删除
for(var i=num;i>0;i--){
$('#tab').tabs('close',i);
}
});
})
web层Action
根据我上面的思路,登录进来的时候将用户存到session,然后在这个类里取到用户的type,然后根据这个type查找到中间表对应的pid,再通过topNodePermission方法得到pid对应的权限们,然后通过writeJson方法打印出来。
package com.wangjuanxia.web;
public class PermissionAction extends ActionSupport implements ModelDriver<Permission> {
private Permission permission=new Permission();
private PermissionDao pd=new PermissionDao();
private RolePermissionDao rd=new RolePermissionDao();
@Override
public Permission getModel() {
// TODO Auto-generated method stub
return permission;
}
public String menuTree(HttpServletRequest req,HttpServletResponse resp) {
try {
user u = (user) req.getSession().getAttribute("user");
RolePermission r=new RolePermission();
r.setRid(u.getType());
List<RolePermission> role = this.rd.list(r, null);
StringBuilder pids=new StringBuilder();
for (RolePermission rp : role) {
pids.append(",").append(rp.getPid());
}
List<TreeVo<Permission>> tp = this.pd.topNodePermission(pids.substring(1), null);
ResponseUtil.writeJson(resp, tp);
//ResponseUtil.writeJson(resp, this.pd.topNode(null, null));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
dao方法
package com.wangjuanxia.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangjuanxia.entity.Permission;
import com.wangjuanxia.util.BaseDao;
import com.wangjuanxia.util.BuildTree;
import com.wangjuanxia.util.PageBean;
import com.wangjuanxia.vo.TreeVo;
public class PermissionDao extends BaseDao<Permission>{
/**
* 直接从数据库获取到的数据
* @param menu
* @param pageBean
* @return
* @throws Exception
*/
public List<Permission> list(Permission permission,PageBean pageBean) throws Exception{
String sql="select * from t_easyui_permission";
return super.executeQuery(sql, Permission.class, pageBean);
}
public List<Permission> listPermission(String pids,PageBean pageBean) throws Exception{
String sql="select * from t_easyui_permission where id in ("+pids+")";
return super.executeQuery(sql, Permission.class, pageBean);
}
/**
* 能够将数据库中的数据体现父子结构
* @param menu
* @param pageBean
* @return
* @throws Exception
*/
public List<TreeVo<Permission>> topNode(Permission permission,PageBean pageBean) throws Exception{
List<Permission> list = this.list(permission, pageBean);
List<TreeVo<Permission>> nodes=new ArrayList<TreeVo<Permission>>();
TreeVo treeVo=null;
for (Permission p : list) {
treeVo=new TreeVo<>();
treeVo.setId(p.getId()+"");
treeVo.setText(p.getName());
treeVo.setParentId(p.getPid()+"");
Map<String, Object> attributes=new HashMap<String, Object>();
attributes.put("self", p);
treeVo.setAttributes(attributes);
nodes.add(treeVo);
}
return BuildTree.buildList(nodes,"0");
}
public List<TreeVo<Permission>> topNodePermission(String pids,PageBean pageBean) throws Exception{
List<Permission> list = this.listPermission(pids, pageBean);
List<TreeVo<Permission>> nodes=new ArrayList<TreeVo<Permission>>();
TreeVo treeVo=null;
for (Permission p : list) {
treeVo=new TreeVo<>();
treeVo.setId(p.getId()+"");
treeVo.setText(p.getName());
treeVo.setParentId(p.getPid()+"");
Map<String, Object> attributes=new HashMap<String, Object>();
attributes.put("self", p);
treeVo.setAttributes(attributes);
nodes.add(treeVo);
}
return BuildTree.buildList(nodes,"0");
}
}
效果
管理员登录后:
普通用户登录后:
注意的点:
- jsp页面的表单组件的name一定要跟数据库一模一样
- 当登录的时候如果你登录失败的话sql语句查不到值,可能会报一个IndexOutOfBoundsException的错,这个问题在方法里抛一个对应的异常返回一个“login”意思是当出现这个错误时,就直接跳转到登录页面