如何实现不同用户登录显示不同的菜单模块的权限?
前提需要准备: 开发工具 java环境 tomcat服务器配置 maven的配置 还有Mysql数据库的安装 这些就不给大家一一去说怎么配置以及安装了都非常简单的.
那下面我就用Eclipse开发工具来去怎么实现这么一个根据不同用户显示不同菜单模块的权限
首先在Mysql数据库里面创建好表
menu表
/*
Navicat MySQL Data Transfer
Source Server : MySQL2
Source Server Version : 50720
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50720
File Encoding : 65001
Date: 2019-07-26 16:01:35
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `menu`
-- ----------------------------
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (
`mid` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(200) NOT NULL,
`iconCls` varchar(200) NOT NULL,
`mparent` int(11) NOT NULL DEFAULT '0',
`murl` varchar(200) DEFAULT NULL,
PRIMARY KEY (`mid`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of menu
-- ----------------------------
INSERT INTO `menu` VALUES ('1', '产品管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('3', '产品域管理', 'icon-tip', '1', '');
INSERT INTO `menu` VALUES ('4', '产品型谱', 'icon-tip', '1', '/ssmxm/tree.jsp');
INSERT INTO `menu` VALUES ('6', '文件查询', 'icon-tip', '7', '/ssmxm/papers.jsp');
INSERT INTO `menu` VALUES ('7', '文件管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('8', '零件管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('9', '编码管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('10', '流程管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('11', '零件查询', 'icon-tip', '8', null);
INSERT INTO `menu` VALUES ('12', 'BOM比较', 'icon-tip', '8', null);
INSERT INTO `menu` VALUES ('13', '编码规则', 'icon-tip', '9', null);
INSERT INTO `menu` VALUES ('14', '编码型谱', 'icon-tip', '9', '/ssmxm/index.jsp');
INSERT INTO `menu` VALUES ('15', '我的任务', 'icon-tip', '10', null);
INSERT INTO `menu` VALUES ('16', '我参与的流程', 'icon-tip', '10', null);
INSERT INTO `menu` VALUES ('17', '我的消息', 'icon-tip', '10', null);
INSERT INTO `menu` VALUES ('18', '存储库管理', 'icon-print', '0', null);
INSERT INTO `menu` VALUES ('19', '存储管理', 'icon-tip', '18', null);
INSERT INTO `menu` VALUES ('20', '用户管理', 'icon-print', '0', '');
INSERT INTO `menu` VALUES ('21', '用户信息', 'icon-tip', '20', '/ssmxm/users.jsp');
users表
/* Navicat MySQL Data Transfer Source Server : MySQL2 Source Server Version : 50720 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50720 File Encoding : 65001 Date: 2019-07-26 16:01:53 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `users` -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(200) NOT NULL, `password` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES ('1', 'admin', '123456'); INSERT INTO `users` VALUES ('2', 'users', '123456'); INSERT INTO `users` VALUES ('3', '小敏', '123456'); INSERT INTO `users` VALUES ('5', '小哥', '123456'); INSERT INTO `users` VALUES ('6', '小强', '123456'); INSERT INTO `users` VALUES ('8', '小花', '123456'); INSERT INTO `users` VALUES ('10', '潇潇', '123456'); INSERT INTO `users` VALUES ('37', 'Q仔', '123456'); INSERT INTO `users` VALUES ('38', '小张', '123456'); INSERT INTO `users` VALUES ('44', '香茗', '123456'); INSERT INTO `users` VALUES ('45', '顾森西', '123456'); INSERT INTO `users` VALUES ('46', '齐铭', '123456'); INSERT INTO `users` VALUES ('47', '易遥', '123456');
role表
/* Navicat MySQL Data Transfer Source Server : MySQL2 Source Server Version : 50720 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50720 File Encoding : 65001 Date: 2019-07-26 16:01:41 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `role` -- ---------------------------- DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `rid` int(100) NOT NULL AUTO_INCREMENT, `rname` varchar(200) DEFAULT NULL, `uid` int(100) DEFAULT NULL, PRIMARY KEY (`rid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of role -- ---------------------------- INSERT INTO `role` VALUES ('1', 'admin', '1'); INSERT INTO `role` VALUES ('2', 'users', '2');
user_role表
/* Navicat MySQL Data Transfer Source Server : MySQL2 Source Server Version : 50720 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 50720 File Encoding : 65001 Date: 2019-07-26 16:01:46 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `user_role` -- ---------------------------- DROP TABLE IF EXISTS `user_role`; CREATE TABLE `user_role` ( `rid` int(100) NOT NULL, `mid` int(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user_role -- ---------------------------- INSERT INTO `user_role` VALUES ('1', '7'); INSERT INTO `user_role` VALUES ('1', '1'); INSERT INTO `user_role` VALUES ('2', '1'); INSERT INTO `user_role` VALUES ('1', '8'); INSERT INTO `user_role` VALUES ('1', '9'); INSERT INTO `user_role` VALUES ('2', '18'); INSERT INTO `user_role` VALUES ('2', '7'); INSERT INTO `user_role` VALUES ('2', '9'); INSERT INTO `user_role` VALUES ('2', '10'); INSERT INTO `user_role` VALUES ('1', '20');
pojo实体类就忽略
users.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zking.dao.IUsersDao"> <select id="getRid" resultType="java.lang.Integer"> select r.rid from users u INNER JOIN role r on u.id=r.rid where u.username=#{username} and u.password=#{password} </select> <select id="getAll" resultType="users"> select u.id,u.username,u.password from users u where 1=1 <if test="username!=null or username==''"> and u.username like '%' #{username} '%' </if> ORDER BY u.id DESC LIMIT #{page},#{end} </select> <select id="getCount" resultType="java.lang.Integer"> select count(u.id) from users u where 1=1 <if test="username!=null or username==''"> and u.username like '%' #{username} '%' </if> </select> <delete id="deleteUsers" parameterType="java.lang.Integer"> delete from users where id=#{id} </delete> <insert id="insertUsers" parameterType="users"> insert into users(username,password) values(#{username},#{password}); </insert> </mapper>
menu.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zking.dao.IMenuDao"> <select id="getParent" resultType="Menu"> select m.* from menu m INNER JOIN user_role u on m.mid=u.mid where u.rid=#{rid} </select> <select id="getMenuAll" resultType="Menu"> select m.* from menu m where m.mparent = (select m.mid from menu m where m.text=#{text}) </select> </mapper>
dao层
IMenuDao接口
package com.zking.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.zking.pojo.Menu; public interface IMenuDao { public List<Menu> getParent(int rid); public List<Menu> getMenuAll(String mname); }
IUsersDao接口
package com.zking.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.zking.pojo.Users; import com.zking.pojo.UsersVo; public interface IUsersDao { public List<Users> getAll(UsersVo uv); public int getCount(UsersVo uv); public int insertUsers(Users us); public int deleteUsers(int id); public List<Users> login(String username,String password); public int getRid(@Param("username") String username,@Param("password") String password); }
service层
IMenuService接口
package com.zking.service; import java.util.List; import com.zking.pojo.Menu; public interface IMenuService { public List<Menu> getParent(int rid); public List<Menu> getMenuAll(String mname); }
MenuServiceImpl类
package com.zking.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zking.dao.IMenuDao; import com.zking.pojo.Menu; import com.zking.service.IMenuService; @Service public class MenuServiceImpl implements IMenuService{ @Autowired private IMenuDao imd; public List<Menu> getParent(int rid) { // TODO Auto-generated method stub return imd.getParent(rid); } public List<Menu> getMenuAll(String mname) { // TODO Auto-generated method stub return imd.getMenuAll(mname); } }
IUsersService接口
package com.zking.service; import java.util.List; import com.zking.pojo.Users; import com.zking.pojo.UsersVo; public interface IUsersService { public int getRid(String username,String password); public List<Users> getAll(UsersVo uv); public int getCount(UsersVo uv); public int insertUsers(Users us); public int deleteUsers(int id); public List<Users> login(String username,String password); }
UsersServiceImpl类
package com.zking.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zking.dao.IUsersDao; import com.zking.pojo.Users; import com.zking.pojo.UsersVo; import com.zking.service.IUsersService; @Service public class UsersServiceImpl implements IUsersService{ @Autowired private IUsersDao iud; public int getRid(String username, String password) { // TODO Auto-generated method stub return iud.getRid(username, password); } public List<Users> getAll(UsersVo uv) { // TODO Auto-generated method stub return iud.getAll(uv); } public int getCount(UsersVo uv) { // TODO Auto-generated method stub return iud.getCount(uv); } public int insertUsers(Users us) { // TODO Auto-generated method stub return iud.insertUsers(us); } public int deleteUsers(int id) { // TODO Auto-generated method stub return iud.deleteUsers(id); } public List<Users> login(String username, String password) { // TODO Auto-generated method stub return iud.login(username, password); } }
controller层
MenuController类
package com.zking.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.zking.pojo.Menu; import com.zking.service.IMenuService; import net.sf.json.JSONArray; @Controller public class MenuController { @Autowired private IMenuService ims; @RequestMapping(value = "/getParent") public void getParent(HttpServletResponse response, HttpServletRequest request) throws Exception { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); // 开始访问数据库 List<Menu> lm = null; String mname=request.getParameter("text"); // 是不是获取到值 System.out.println(mname); if (mname != null) { lm = ims.getMenuAll(mname); } else { HttpSession session = request.getSession(); int rid = Integer.parseInt(session.getAttribute("rid").toString()); lm = ims.getParent(rid); } PrintWriter out = response.getWriter(); JSONArray jsonArray = JSONArray.fromObject(lm); String str = jsonArray.toString(); System.out.println(str); // 输出 out.print(str); out.flush(); out.close(); } }
UsersController类
package com.zking.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.zking.pojo.Users; import com.zking.pojo.UsersVo; import com.zking.service.IUsersService; import net.sf.json.JSONObject; @Controller public class UsersController { @Autowired private IUsersService ius; @RequestMapping(value = "/getRid") public void getRid(HttpServletResponse response, HttpServletRequest request) throws Exception { String username = request.getParameter("username"); String password = request.getParameter("password"); int rid = ius.getRid(username, password); // 把rid传给MenuServlet HttpSession session = request.getSession(); session.setAttribute("rid", rid); session.setAttribute("username", username); PrintWriter out = response.getWriter(); // 返回登录信息 if (rid > 0) { out.write("Y"); } else { out.write("N"); } out.flush(); out.close(); } @RequestMapping(value = "/getAll") public void getAll(HttpServletResponse response, HttpServletRequest request) throws IOException { String username = request.getParameter("username"); int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page")); int rows = request.getParameter("rows") == null ? 5 : Integer.parseInt(request.getParameter("rows")); UsersVo uv = new UsersVo(); uv.setUsername(username); uv.setPage((page - 1) * rows); uv.setEnd(rows); List<Users> list = ius.getAll(uv); int max = ius.getCount(uv); JSONObject json = new JSONObject(); json.put("rows", list); json.put("total", max); String str = json.toString(); PrintWriter out = response.getWriter(); out.write(str); out.flush(); out.close(); } @RequestMapping(value="/insertUsers") public String insertUsers (Users u,HttpServletResponse response, HttpServletRequest request) throws IOException { int index=ius.insertUsers(u); System.out.println(index); return "redirect:/users.jsp"; } @RequestMapping(value="/deleteUsers") public String deleteUsers(HttpServletResponse response, HttpServletRequest request) throws Exception{ int id=Integer.parseInt(request.getParameter("id")); int index= ius.deleteUsers(id); PrintWriter out=response.getWriter(); String str=""; if(index>0){ str= "true"; }else{ str= "false"; } out.print(str); out.flush(); out.close(); return str; } }
下面就是前端界面代码,前端页面用的是easyui框架所以在用的时候需要导入对应的css和js文件
easyui文件
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> <%@ include file="head.jsp" %> <script type="text/javascript"> function login(){ $.ajax({ url:'getRid.action', type:'post', datatype:'text', data:{ username:$('#username').textbox('getValue'), password:$('#password').textbox('getValue') }, success:function(data){ if(data=="Y"){ $.messager.show({ title:'登录信息', msg:'登录成功', timeout:4000, showType:'slide', onClose:function(){ window.location.href='menu.jsp'; } }); } else{ $.messager.show({ title:'登录信息', msg:'登录失败', timeout:4000, showType:'slide', }); } } }); } function loings(){ if (event.keyCode==13){ //回车键的键值为13 document.getElementById("btn").click(); //调用登录按钮的登录事件 } } </script> </head> <body onkeydown="loings();"> <div align="center"> <h2>用户登录</h2> 用户名:<input class="easyui-textbox" id="username" ><br/><br/> 密 码:<input class="easyui-passwordbox" id="password" ><br/> <br/> <a id="btn" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="login();">登录</a> </div> </body> </html>
menu.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>Insert title here</title> <jsp:include page="head.jsp"></jsp:include> <link rel="stylesheet" type="text/css" href="css/wu.css"> <script type="text/javascript"> $(function(){ $.ajax({ url:"getParent.action", type:"post", // contentType:"application/json;charset=utf-8", datatype:"json", success:function(data){ var d=$.parseJSON(data); //控制台输出 console.log(d); $.each(d,function(index,m){ console.log(index+"-------"+m.mid); var flag=false; if(m.mid==1){ flag=true; } $('#accordion').accordion('add',{ title:m.text, content:'<div id='+m.text+'></div>', selected:flag }); }); } }); // $('#accordion').accordion("select","0"); $('#accordion').accordion({ onSelect:function(title,index){ console.log(title) $('#'+title).tree({ url:"getParent.action", queryParams:{ text:title }, method:"post", animate:true, onClick:function(node){ //alert(node.mname); addtabs(node.text,node.murl); } }); } }); }); function addtabs(title,url){ // alert(title+"------"+url); if($('#tabs').tabs('exists',title)){ $('#tabs').tabs('select',title) }else{ $('#tabs').tabs('add',{ title:title, content: '<iframe src=' + url + ' style="100%;height:95%;"></iframe>', closable:true, }); } } //easyui鼠标右键功能 $(function() { //生成tab标签 $('#tabs').tabs({ border : true, /* onSelect : function(title) { alert(title + ' is selected'); } */ }); //生成右键菜单 $('#tabs').tabs({ onContextMenu: function(e, title, index){ //选中标签 $('#tabs').tabs('select',index); //显示右键菜单 $('#mm').menu('show', { left: e.pageX, top: e.pageY }) ; } }); //为每个菜单绑定点击事件 //关闭选中的标签 $("#closeCurrent").click(function(){ //获取选中的标签索引 var tab = $('#tabs').tabs('getSelected'); var index = $('#tabs').tabs('getTabIndex',tab); $("#tabs").tabs("close",index); }); //关闭选中标签之外的标签 $("#closeOthers").click(function(){ //获取所有标签 var tabs = $("#tabs").tabs("tabs"); var length = tabs.length; //获取选中标签的索引 var tab = $('#tabs').tabs('getSelected'); var index = $('#tabs').tabs('getTabIndex',tab); //关闭选中标签之前的标签 for(var i=0;i<index;i++){ $("#tabs").tabs("close",0); } //关闭选中标签之后的标签 for(var i=0;i<length-index-1;i++){ $("#tabs").tabs("close",1); } }); //关闭所有标签 $("#closeAll").click(function(){ var tabs = $("#tabs").tabs("tabs"); var length = tabs.length; for(var i=0;i<length;i++){ $("#tabs").tabs("close",0); } }); }); function login(){ if(confirm("您确认退出登录吗?")) { location.href="login.jsp"; }; return false; } </script> <script type="text/javascript"> //浏览器禁用鼠标右键 document.oncontextmenu=function(e) { // alert(“我是鼠标右键弹框”); return false; } </script> </head> <body class="easyui-layout"> <div class="wu-header" data-options="region:'north',border:false,split:true"> <div class="wu-header-left"> <h1>EasyUI Web Admin</h1> </div> <div align="right" style="padding-top: 15px;padding-right: 20px;"> <a class="easyui-linkbutton" onclick="login();">登录</a> </div> </div> <div data-options="region:'east',iconCls:'icon-reload',split:true" style="0px;"></div> <div data-options="region:'west',title:'菜单',iconCls:'icon-more',split:true" style="200px;"> <div id="accordion" class="easyui-accordion" data-options="border:false,fit:true" style="194px;"> </div> </div> <div data-options="region:'center'" > <div id="tabs" class="easyui-tabs" data-options="fit:true" style="100%;height:95%;"> </div> </div> <div data-options="region:'south',split:true,border:true" style="text-align: center; padding: 20px;">©湖南软件</div> <div id="mm" class="easyui-menu" style="120px;"> <div id="closeCurrent" name="closeCurrent" >关闭当前</div> <div id="closeOthers" name="closeOthers" >关闭其它</div> <div id="closeAll" name="closeAll" >关闭所有</div> </div> </body> </html>