权限验证
1.创建数据库,然后测试菜单权限的联合查询语句;
2.创建项目,导入jar包,配置实体类和工具类
3.完成登录功能,当输入用户名和密码正确后跳转到框架页面
- 编写导航页(top.jsp)和内容页(main.jsp);
- 在框架页中加载 导航页 和 内容页;
- 加载菜单页的位置写的是后端的请求地址
4.完成菜单请求,根据当前用户获得该用户的菜单权限,并在菜单页中显示
- 菜单请求的servlet
- 菜单请求的dao层代码
- 菜单页面进行遍历集合并展示数据
1.数据库
/*
Navicat Premium Data Transfer
Source Server : 2105
Source Server Type : MySQL
Source Server Version : 80016
Source Host : localhost:3306
Source Schema : mydb
Target Server Type : MySQL
Target Server Version : 80016
File Encoding : 65001
Date: 02/06/2023 10:23:19
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for menu
-- ----------------------------
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (
`mid` int(11) NOT NULL,
`mname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`mid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of menu
-- ----------------------------
INSERT INTO `menu` VALUES (1, '部门管理');
INSERT INTO `menu` VALUES (2, '员工管理');
INSERT INTO `menu` VALUES (3, '产品管理');
INSERT INTO `menu` VALUES (4, '客户管理');
INSERT INTO `menu` VALUES (5, '订单管理');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`rid` int(11) NOT NULL,
`rname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`rid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, '超级管理员');
INSERT INTO `role` VALUES (2, '总经理');
INSERT INTO `role` VALUES (3, '主管');
INSERT INTO `role` VALUES (4, '员工');
-- ----------------------------
-- Table structure for role_menu
-- ----------------------------
DROP TABLE IF EXISTS `role_menu`;
CREATE TABLE `role_menu` (
`rmid` int(11) NOT NULL,
`rid` int(11) DEFAULT NULL,
`mid` int(11) DEFAULT NULL,
PRIMARY KEY (`rmid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role_menu
-- ----------------------------
INSERT INTO `role_menu` VALUES (1, 1, 1);
INSERT INTO `role_menu` VALUES (2, 1, 2);
INSERT INTO `role_menu` VALUES (3, 1, 3);
INSERT INTO `role_menu` VALUES (4, 1, 4);
INSERT INTO `role_menu` VALUES (5, 1, 5);
INSERT INTO `role_menu` VALUES (6, 2, 1);
INSERT INTO `role_menu` VALUES (7, 2, 2);
INSERT INTO `role_menu` VALUES (8, 2, 3);
INSERT INTO `role_menu` VALUES (9, 3, 1);
INSERT INTO `role_menu` VALUES (10, 3, 2);
INSERT INTO `role_menu` VALUES (11, 4, 4);
INSERT INTO `role_menu` VALUES (12, 4, 5);
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`uname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`state` int(5) DEFAULT NULL,
PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', '111', '郑州', 1);
INSERT INTO `user` VALUES (2, 'zs', '222', '洛阳', 1);
INSERT INTO `user` VALUES (3, 'ls', '333', '南阳', 1);
INSERT INTO `user` VALUES (4, 'xm', '444', '安阳', 1);
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`urid` int(11) NOT NULL,
`uid` int(11) DEFAULT NULL,
`rid` int(11) DEFAULT NULL,
PRIMARY KEY (`urid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1, 1);
INSERT INTO `user_role` VALUES (2, 2, 2);
INSERT INTO `user_role` VALUES (3, 2, 4);
INSERT INTO `user_role` VALUES (4, 3, 3);
INSERT INTO `user_role` VALUES (5, 3, 4);
INSERT INTO `user_role` VALUES (6, 4, 4);
SET FOREIGN_KEY_CHECKS = 1;
#测试数据
drop PROCEDURE if exists addTestData;
#--创建存储过程,用来插入测试数据
delimiter $
CREATE PROCEDURE addTestData(IN n int)
BEGIN
DECLARE i int DEFAULT 1;
WHILE (i <= n ) DO
INSERT into `user`(uname,pwd,address,state) VALUES(concat('test',i),'111',concat('地址',i),1);
set i=i+1;
END WHILE;
END;
$
#--调用
call addTestData(100);
select * from `user`;
#从第 0 条开始,查询3条(每页显示的条数)
select * from `user` limit 0,10; #第一页
select * from `user` limit 10,10; #第二页
select * from `user` limit 20,10; #第三页
select * from `user` limit 30,10; #第四页
#查询第m页,每页显示n条 请写出表达式
# 每页数量 当前页数 总条数 总页数 = (总条数%每页数量==0) ? 总条数/每页数量 : (总条数/每页数量)+1
select count(uid) num from `user`;
#查询ls的菜单权限
#查询ls的uid
select uid from user where uname='ls';
#查询该uid 对应 的 rid
select rid from user_role where uid=3;
#查询 rid 对应的 mid
select mid from where rid in(3,4);
#查询mid 对应的 菜单名
select mname from menu where mid in(1,2,4,5);
#多表联查
select mname from user u
inner join user_role ur on u.uid=ur.uid
inner join role_menu rm on ur.rid=rm.rid
inner join menu m on rm.mid=m.mid
where u.uid=3;
select mname from user u inner join user_role ur on u.uid=ur.uid;
2.web项目,导入jar包;配置实体类User和工具类JDBCUtil
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>菜单权限</title>
</head>
<body>
<form action="login" method="post">
帐号:<input type="text" name="uname" value=""><br/>
密码:<input type="password" name="pwd" value=""><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
页面效果
头部导航:top.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>头部</title>
<style>
*{
margin: 0px;
padding: 0px;
}
a{
text-decoration: none;
}
ul,ol{
list-style: none;
}
body{
background-color: steelblue;
}
#nav{
margin-left: 280px;
}
#nav ul li a{
display: block;
width: 120px;
height: 55px;
line-height: 55px;
/* border: 1px blue solid; */
text-align: center;
float: left;
font-size: 18px;
color: white;
font-weight: 700;
}
#nav ul li a:hover{
background-color: midnightblue;
}
</style>
</head>
<div id="nav">
<ul>
<li><a href="main.jsp" target="mainFrame">网站首页</a></li>
<li><a href="#">公司产品</a></li>
<li><a href="#">企业文化</a></li>
<li><a href="#">公司新闻</a></li>
<li><a href="#">系统设置</a></li>
</ul>
</div>
</html>
左侧菜单:menu.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>左侧菜单</title>
<style>
*{
margin: 0px;
padding: 0px;
}
a{
text-decoration: none;
}
ul,ol{
list-style: none;
}
body{
background-color: steelblue;
}
h2{
text-align: center;
}
#menu{
width: 150px;
margin: 10px auto;
}
#menu ul li p{
display: block;
width: 150px;
height: 35px;
line-height: 35px;
/* border: 1px red solid; */
text-align: center;
font-size: 18px;
color: white;
font-weight: 700;
}
#menu ul li ol li a{
display: block;
width: 150px;
height: 35px;
line-height: 35px;
/* border: 1px green solid; */
text-align: center;
font-size: 18px;
color: white;
font-weight: 700;
}
#menu ul li ol li a:hover{
background-color: cadetblue;
}
#menu ul li ol{
display: none;
}
</style>
<script src="js/jquery.min.js"></script>
<script>
$(function(){
$("#menu ul li").click(function(){
var state=$(this).children("ol").css("display");
if(state=="none"){
$(this).children("ol").slideDown();
$(this).siblings().children("ol").slideUp();
}else{
$(this).children("ol").slideUp();
}
})
})
</script>
</head>
<body>
<h2>系统菜单</h2>
<div id="menu">
<%-- <ul>--%>
<%-- <c:forEach items="${menuList}" var="menu">--%>
<%-- <li><p><a href="#">${menu.mname}</a></p></li>--%>
<%-- </c:forEach>--%>
<%-- </ul>--%>
<ul>
<li>
<p>部门管理</p>
<ol>
<li><a href="研发部.jsp" target="mainFrame">--研发部</a></li>
<li><a href="财务部.jsp" target="mainFrame">--财务部</a></li>
<li><a href="市场部.jsp" target="mainFrame">--市场部</a></li>
</ol>
</li>
<li>
<p>产品管理</p>
<ol>
<li><a href="#">--产品发布</a></li>
<li><a href="#">--产品维护</a></li>
<li><a href="#">--产品下架</a></li>
</ol>
</li>
<li>
<p>订单管理</p>
<ol>
<li><a href="#">--客户录入</a></li>
<li><a href="#">--订单审核</a></li>
<li><a href="#">--订单维护</a></li>
</ol>
</li>
<li>
<p>系统设置</p>
<ol>
<li><a href="#">--字典管理</a></li>
<li><a href="#">--参数设置</a></li>
<li><a href="#">--内存管理</a></li>
</ol>
</li>
</ul>
</div>
</body>
</html>
右侧内容:main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>内容</title>
<style>
/*img{*/
/* width: 1000px;*/
/* height: 1000px;*/
/*}*/
</style>
</head>
<body>
<div>
<%-- <img src="img/lyy.jpg" />--%>
<img src="img/boy.jpg" />
</div>
</body>
</html>
以上三部分整合frame.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<frameset rows="56,*" border="1">
<frame src="top.jsp" />
<frameset cols="150,*">
<frame src="getMenu" />
<frame src="main.jsp" name="mainFrame" />
</frameset>
</frameset>
</html>
市场部.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>市场部</h2>
</body>
</html>
研发部.jsp、财务部.jsp;同上
页面效果
dao层
UserDao接口
public interface UserDao {
User selectByName(String uname) throws SQLException;
List<Map<String, Object>> getMenuByUid(int uid) throws SQLException;
}
UserDaoImpl实现类
public class UserDaoImpl implements UserDao {
private QueryRunner queryRunner = new QueryRunner();
private Connection conn = JDBCUtil.getConnection();
private String sql = null;
@Override
public User selectByName(String uname) throws SQLException {
sql="select * from user where uname=?";
BeanHandler<User> userBeanHandler = new BeanHandler<>(User.class);
User user = queryRunner.query(conn, sql, userBeanHandler, uname);
return user;
}
@Override
public List<Map<String, Object>> getMenuByUid(int uid) throws SQLException {
sql="select mname from user u " +
"inner join user_role ur on u.uid=ur.uid " +
"inner join role_menu rm on ur.rid=rm.rid " +
"inner join menu m on rm.mid=m.mid " +
"where u.uid=? ";
MapListHandler mapListHandler = new MapListHandler();
List<Map<String, Object>> list = queryRunner.query(conn, sql, mapListHandler, uid);
return list;
}
}
service层
UserService接口
public interface UserService {
User selectByName(String uname);
List<Map<String, Object>> getMenuByUid(int uid);
}
UserServiceImpl实现类
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
@Override
public User selectByName(String uname) {
try {
return userDao.selectByName(uname);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Map<String, Object>> getMenuByUid(int uid) {
try {
return userDao.getMenuByUid(uid);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
servlet层
UserGetMenu.java
@WebServlet("/getMenu")
public class UserGetMenu extends HttpServlet {
UserService userService = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String uname = request.getParameter("uname");
// System.out.println(uname);
// User user = userService.selectByName(uname);
// System.out.println(user);
//从session域中拿到登录的用户信息
User user = (User) request.getSession().getAttribute("user");
List<Map<String, Object>> menuList = userService.getMenuByUid(user.getUid());
// System.out.println(menuList);
request.setAttribute("menuList",menuList);
// request.getRequestDispatcher("zhuye.jsp").forward(request,response);
request.getRequestDispatcher("menu.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
登录UserLogin
@WebServlet("/login")
public class UserLogin extends HttpServlet {
UserService userService = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
User user = userService.selectByName(uname);
if(user.getPwd().equals(pwd)){
request.getSession().setAttribute("user",user);
response.sendRedirect("frame.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
分页
测试数据MySQL
#测试数据
drop PROCEDURE if exists addTestData;
#--创建存储过程,用来插入测试数据
delimiter $
CREATE PROCEDURE addTestData(IN n int)
BEGIN
DECLARE i int DEFAULT 1;
WHILE (i <= n ) DO
INSERT into `user`(uname,pwd,address,state) VALUES(concat('test',i),'111',concat('地址',i),1);
set i=i+1;
END WHILE;
END;
$
#--调用
call addTestData(100);
dao层
UserDao接口
public interface UserDao {
// User selectByName(String uname) throws SQLException;
//
// List<Map<String, Object>> getMenuByUid(int uid) throws SQLException;
int selectCount() throws SQLException;
List<User> selectByPage(int pageNo, int pageSize) throws SQLException;
}
接口实现类:UserDaoImpl.java
public class UserDaoImpl implements UserDao {
private QueryRunner queryRunner = new QueryRunner();
private Connection conn = JDBCUtil.getConnection();
private String sql = null;
/**
* 获取用户表的总条数
* @return
* @throws SQLException
*/
@Override
public int selectCount() throws SQLException {
sql="select count(uid) num from user";
MapHandler mapHandler=new MapHandler();
Map<String,Object> map = queryRunner.query(conn,sql,mapHandler);
int count=(int)(long)map.get("num"); //默认是Long类型
return count;
}
/**
* 分页查询
* @param pageNo
* @param pageSize
* @return
* @throws SQLException
*/
@Override
public List<User> selectByPage(int pageNo, int pageSize) throws SQLException {
sql="select * from user limit ?,?";
BeanListHandler<User> beanListHandler = new BeanListHandler<>(User.class);
List<User> userList = queryRunner.query(conn, sql, beanListHandler, (pageNo - 1) * pageSize, pageSize);
return userList;
}
}
service层
UserService接口
public interface UserService {
// User selectByName(String uname);
//
// List<Map<String, Object>> getMenuByUid(int uid);
int selectCount();
PageResult selectByPage(int pageNo, int pageSize);
}
UserServiceImpl实现类
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
@Override
public int selectCount() {
try {
return userDao.selectCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public PageResult selectByPage(int pageNo, int pageSize) {
PageResult pageRs = new PageResult();
pageRs.setPageNo(pageNo);//投置当前页数
pageRs.setPageSize(pageSize);//没置每页数量
try {
int totalCount =userDao.selectCount();
List<User> userList = userDao.selectByPage(pageNo,pageSize);
pageRs.setTotalCount(totalCount);//设置总条数
pageRs.setPageTotalCount();//设置总页数
pageRs.setDataList(userList);//设置当前页数据
} catch (SQLException e) {
e.printStackTrace();
}
return pageRs;
}
}
Util层
用来做分页的工具类:PageResult.java
public class PageResult {
//属性
private Integer pageSize; //每页数量
private Integer pageNo;//当前页码
private Integer totalCount;//总条数
private Integer pageTotalCount;//总页数
private List dataList;//用来存储当前页的数据
//方法
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getPageTotalCount() {
return pageTotalCount;
}
public void setPageTotalCount() {
this.pageTotalCount = (totalCount%pageSize==0) ? totalCount/pageSize : (totalCount/pageSize)+1;;
}
public List getDataList() {
return dataList;
}
public void setDataList(List dataList) {
this.dataList = dataList;
}
@Override
public String toString() {
return "PageResult{" +
"pageSize=" + pageSize +
", pageNo=" + pageNo +
", totalCount=" + totalCount +
", pageTotalCount=" + pageTotalCount +
", dataList=" + dataList +
'}';
}
}
查询第m页,每页显示n条
总页数 = (总条数%每页数量==0) ? 总条数/每页数量 : (总条数/每页数量)+1
servlet层
UserListServlet.java
@WebServlet("/userList")
public class UserListServlet extends HttpServlet {
UserService userService = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
int pageNo=1;
int pageSize=10;
String pn = request.getParameter("pageNo");
String ps = request.getParameter("pageSize");
if(pn!=null && pn!=""){
pageNo=Integer.parseInt(pn);
}
if(ps!=null && ps!=""){
pageSize=Integer.parseInt(ps);
}
PageResult pageResult = userService.selectByPage(pageNo, pageSize);
request.setAttribute("pageResult",pageResult);
request.getRequestDispatcher("userList.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
左侧菜单补充
userList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<h2>用户管理</h2>
<table>
<thead>
<tr>
<th>编号</th>
<th>用户</th>
<th>地址</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${pageResult.dataList}" var="user">
<tr>
<td>${user.uid}</td>
<td>${user.uname}</td>
<td>${user.address}</td>
<td>${user.state}</td>
<td>
<a href="#">新增</a>
<a href="#">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<p>
<span>共${pageResult.totalCount}条</span>
<span>当前第${pageResult.pageNo}页</span>
<span>共${pageResult.pageTotalCount}页</span>
</p>
</div>
<form action="userList" method="post">
前往<input type="text" name="pageNo" value="">页
每页<input type="text" name="pageSize" value="">条
<input type="submit" value="跳转">
</form>
<%--当前页:${pageResult.pageNo} <br>--%>
<%--每页数量:${pageResult.pageSize} <br>--%>
<%--总条数:${pageResult.totalCount}<br>--%>
<%--总页数: ${pageResult.pageTotalCount} <br>--%>
<%--当前页数据:${pageResult.dataList} <br>--%>
</body>
</html>
效果图
系统权限五张表
大致用到5张表:用户表(UserInfo)、角色表(RoleInfo)、菜单表(MenuInfo)、用户角色表(UserRole)、角色菜单表(RoleMenu)。
各表的大体表结构如下:
1、用户表(UserInfo):Id、UserName、UserPwd
2、角色表(RoleInfo):Id、RoleName
3、菜单表(MenuInfo):Id、MenuName
4、用户角色表(UserRole):Id、UserId、RoleId
5、角色菜单表(RoleMenu):Id、RoleId、MenuId
JAVA原生实现验证码
编程思路:
- awt包画一个矩形图,填充颜色
- 生成一个四位的随机码值
- 设置各种随机颜色,画干扰线
下载jar包网址:https://mvnrepository.com/