layui二级权限和增删改查
程序员文章站
2022-04-29 08:53:52
...
目录
前言
这个会比较简单,因为就是熟悉一下maven做一下项目和struts,以及layui.
所用界面就只有学生相关信息
所用数据库是之前EasyUI的相关数据库
测试数据1:
uid:000
upwd:123456
测试数据2:
uid:002
upwd:123
jsp界面
index.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">
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/layui/css/layui.css" media="all">
<script src="${pageContext.request.contextPath }/static/jquery-3.3.1.js"></script>
<script src="${pageContext.request.contextPath }/static/layui/layui.js" ></script>
<title>Insert title here</title>
</head>
<body >
<input type="hidden" id="path" value="${pageContext.request.contextPath }" >
<input type="hidden" id="menuHid" value="${menuHid }" >
<div class="layui-layout layui-layout-admin " id="app">
<div class="layui-header">
<div class="layui-logo">后台管理界面</div>
<!-- 头部区域(可配合layui已有的水平导航) -->
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item"><a href="#" onclick="exit()">退出登录</a></li>
</ul>
</div>
<!-- 左边tree页面 -->
<div class="layui-side ">
<div class="layui-side-scroll ">
<div id="demo" ></div>
</div>
</div>
<!-- 选项卡要显示的地方 -->
<div class="layui-body">
<div class="layui-tab" lay-filter="tabs" lay-allowClose="true">
<ul class="layui-tab-title">
</ul>
<div class="layui-tab-content">
</div>
</div>
</div>
<div class="layui-footer" align="center" >
<!-- 底部固定区域 -->
© layui.com - 底部固定区域
</div>
</div>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/layui/layui.all.js"></script>
<script src="${pageContext.request.contextPath }/static/index.js"></script>
</body>
</html>
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>
</head>
<body>
<form action="sy/user_login.action" method="post">
uid:<input type="text" name="uid" ><br>
upwd:<input type="text" name="upwd" ><br>
<input type="submit" >
</form>
</body>
</html>
userMessage.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">
<link rel="stylesheet" href="${pageContext.request.contextPath }/static/layui/css/layui.css" media="all">
<script src="${pageContext.request.contextPath }/static/jquery-3.3.1.js"></script>
<script src="${pageContext.request.contextPath }/static/layui/layui.js" ></script>
<title>Insert title here</title>
</head>
<body>
<div class="child-nav">
<span class="layui-breadcrumb">
<a>用户管理</a>
<a><cite>分类列表</cite></a>
</span>
</div>
<blockquote class="layui-elem-quote">
<!--搜索维度 -->
<div class="layui-form">
<div class="layui-form-item">
<label class="layui-form-label">用户名字</label>
<div class="layui-input-inline">
<input type="text" id='reuname' name="reuname" lay-verify="required" placeholder="请输入姓名" autocomplete="true" class="layui-input">
</div>
<button class="layui-btn layui-btn-normal layui-btn-radius" data-type="reload"><i class="layui-icon"></i>查询</button>
<button class="layui-btn layui-btn-normal" data-type="add">新建</button>
</div>
</div>
</blockquote>
<!--隐藏域传值 -->
<input type="hidden" id="sj" value="${pageContext.request.contextPath}" >
<!--根据table id 来展示表格数据 -->
<table class="layui-hide" id="test" lay-filter="test"></table>
<!--行内样式按钮 -->
<script type="text/html" id="lineBtns">
<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon"></i>编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!--弹出层 -->
<div class="site-text" style="margin: 5%; display: none" id="box1" target="test123">
<form class="layui-form layui-form-pane" onsubmit="return false" id="booktype">
<input type="hidden" name="SerialNo" id="SerialNo" >
<div class="layui-form-item">
<label class="layui-form-label">用户编号</label>
<div class="layui-input-block">
<input type="text" class="layui-input " name="uid" id="uid">
</div>
<br>
<label class="layui-form-label"> 用户姓名</label>
<div class="layui-input-block">
<input type="text" class="layui-input" name="uname" id="uname" ><br>
</div>
<label class="layui-form-label"> 用户密码</label>
<div class="layui-input-block">
<input type="text" class="layui-input" name="upwd" id="upwd" ><br>
</div>
</div>
</form>
</div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/layui/layui.all.js"></script>
<script src="${pageContext.request.contextPath }/static/userMessage.js"></script>
</body>
</html>
js
index.js
$(function () {
var path = $("#path").val();
$.ajax({
type: "post",
url: path+"/sy/menu_treeMenu.action?menuHid="+$("#menuHid").val(),
dataType: "json",
/*data: {// 传给servlet的数据,
role_id: MenuHid,
right_code: "-1",
d: new Date()
},*/
success: function (data) {
console.info(data);
layui.tree({
elem: '#demo',// 传入元素选择器
nodes: data,
// spread:true,
click: function (node) {// 点击tree菜单项的时候
var element = layui.element;
var exist = $("li[lay-id='" + node.id + "']").length;//判断是不是用重复的选项卡
if (exist > 0) {
element.tabChange('tabs', node.id);// 切换到已有的选项卡
} else {
if (node.attributes.menuURL != null && node.attributes.menuURL != "") {// 判断是否需要新增选项卡
element.tabAdd(
'tabs',
{
title: node.name,
content: '<iframe scrolling="yes" frameborder="0" src="'
+ node.attributes.menuURL
+ '" width="100%" height="100%"></iframe>'// 支持传入html
,
// width="99%" height="99%"
id: node.id
});
element.tabChange('tabs', node.id);
}
}
}
});
}
});
})
userMessage.js
//执行渲染
layui.use(['table','layer','form'],function(){
var data=document.getElementById("sj").value;
var table =layui.table;
var layer=layui.layer;
var form = layui.form;
/*展示数据表格 */
table.render({
elem:'#test'//表格id
,url:data+'/sy/user_editlist.action'//所对应调用的接口
,method:'post' //提交方式
,cols:[[
/*根据数据库的表格所对应的名称 */
{field:'uid',height:80, width:300, title: '用户id', sort: true}
,{field:'uname', height:80,width:300, title: '用户名字'}
,{field:'upwd',height:80, width:300, title: '用户密码'}
,{field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作栏
]]
,page:true
, id: 'testReload'
});
//上方菜单操作栏(查询、以及 增加 按钮 )
var $ = layui.$, active = {
//查询
reload: function () {
var uname = $('#reuname');//用户名称 根据 id来取值
console.log(uname.val());
// 执行重载
table.reload('testReload', {
page: {
curr: 1
// 重新从第 1 页开始
},
where: {
key: 'uname',
uname: uname.val(),
}
});
}, add: function () { //添加
layer.open({//弹出框
type: 1,
title: '添加用户',
maxmin: true,
shadeClose: true, //点击遮罩关闭层
area: ['80%', '80%'],
content: $('#box1'),
btn: ['确定', '取消'],
yes: function (index, layero) {//确定执行函数
console.log(layero);
//执行添加方法
$.getJSON(data+"/sy/user_adduser.action", {
uid: $("#uid").val(),
uname:$("#uname").val(),
upwd:$("#upwd").val()
}, function (data) {
/*根据后台返回的参数来进行判断 */
if (data==1) {
layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
layer.close(index);//关闭弹出层
layer.style(index, {
margin: '5%', display: 'none',
});
})
table.reload('testReload', {//重载表格
page: {
curr: 1
// 重新从第 1 页开始
}
})
} else if(data==2){
$("#booktype")[0].reset()//重置form 根据id
layer.close(index);//关闭弹出层
layer.msg('添加失败,请勿重复添加书本类别名称')
}
})
}, cancel: function (index, layero) {//取消
$("#booktype")[0].reset()//重置form 根据id
layer.close(index)
}
});
}
}
$('.layui-form .layui-btn').on('click', function () {
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
/*表格 行内操作(编辑 以及 删除 按钮操作) */
table.on('tool(test)', function(obj){
var data = obj.data; //获得当前行数据
var urlex=document.getElementById("sj").value;
var tr=obj.tr//活动当前行tr 的 DOM对象
console.log(data);
var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
if(layEvent === 'del'){ //删除
layer.confirm('确定删除吗?',{title:'删除'}, function(index){
//向服务端发送删除指令og
$.getJSON(urlex+"/sy/user_deluser.action",{SerialNo:data.SerialNo}, function(ret){
layer.close(index);//关闭弹窗
layer.style(index, {
margin: '5%', display: 'none',
});
table.reload('testReload', {//重载表格
page: {
curr: 1
// 重新从第 1 页开始
}
})
});
layer.close(index);
});
} else if(layEvent === 'edit'){ //编辑
layer.open({
type: 1 //Page层类型
,skin: 'layui-layer-molv'
,area: ['380px', '270px']
,title: ['编辑用户信息','font-size:18px']
,btn: ['确定', '取消']
,shadeClose: true
,shade: 0 //遮罩透明度
,maxmin: true //允许全屏最小化
,content:$('#box1') //弹窗id
,success:function(layero,index){
$('#SerialNo').val(data.SerialNo);
$('#uid').val(data.uid);
$('#uname').val(data.uname);
$('#upwd').val(data.upwd);
},yes:function(index,layero){
/* $.ajaxSettings.async = false; */
$.getJSON(urlex+"/sy/user_edituser.action",{
uid: $("#uid").val(),
uname:$("#uname").val(),
upwd:$("#upwd").val() ,
SerialNo:$("#SerialNo").val()
},function(data){
//根据后台返回的参数,来进行判断
if(data>0){
layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
layer.close(i);
layer.close(layer.index);//关闭弹出层
layer.style(index, {
margin: '5%', display: 'none',
});
$("#booktype")[0].reset()//重置form
})
table.reload('testReload',{//重载表格
page:{
curr:1
}
})
}
});
}
});
}
});
});
配置文件
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liwangwang</groupId>
<artifactId>T224</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>T224 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- struts2核心包 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.13</version>
</dependency>
<!-- EL表达式 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- EL表达式 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 5.4、tomcat-jsp-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>8.0.47</version>
</dependency>
<!-- 5.4、转换为json的格式 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
<build>
<finalName>T224</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.liwangwang.crud.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts-sy.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="sy" extends="base" namespace="/sy">
<action name="/menu_*" class="com.liwangwang.crud.web.MenuAction" method="{1}" >
<result name="rs">/rs.jsp</result>
</action>
<action name="/user_*" class="com.liwangwang.crud.web.UserAction" method="{1}" >
<result name="index">/index.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
dao
MenuDao
package com.liwangwang.crud.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.liwangwang.crud.entity.TreeNode;
import com.liwangwang.crud.util.JsonBaseDao;
import com.liwangwang.crud.util.JsonUtils;
import com.liwangwang.crud.util.PageBean;
import com.liwangwang.crud.util.StringUtils;
public class MenuDao extends JsonBaseDao{
/*格式:menu: 类型 意思
* menuid String 表id
* menuname String 名字
* menuURL String 路径
* parentid String 上一级的id
* treeNode:
* id String 节点的id
* text String 节点的名字
* children List<treeNode> 该节点下的子节点
* attributes map<String,Object>节点的对应路径
*
*/
//流程:第一步
public List<TreeNode> list(Map<String, String[]> map,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
List<Map<String, Object>> listMenu = this.listMenuSef(map, pageBean);//调用查询数据库的方法来获取数据
List<TreeNode> treeNodesList = new ArrayList<>();//先搞一个容器准备装着
menuList2TreeNodeList(listMenu, treeNodesList);//调用来将查询过来的menu数据转换为treeNode数据
return treeNodesList;
}
//流程之外
public List<Map<String, Object>> listMenuSef(Map<String, String[]> map,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_easyui_menu where true ";
String id = JsonUtils.getParamVal(map, "menuHid");//这个是从jsp界面传过来的
if(StringUtils.isNotBlank(id)) {
sql = sql + " and Menuid in ("+id+") ";
}else {
sql = sql + " and Menuid = -1";
}
return super.executeQuery(sql, pageBean);
}
/**
* 查询menu表的数据
* @param map
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
//流程:第二步
public List<Map<String, Object>> listMenu(Map<String, String[]> map,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_easyui_menu where true ";
String id = JsonUtils.getParamVal(map, "id");//第一次为空
if(StringUtils.isNotBlank(id)) {
sql = sql + " and parentid = "+id;
}else {
sql = sql + " and parentid = -1";//在第一次的时候执行
}
return super.executeQuery(sql, pageBean);
}
/**转换的单个转换
*
* menu表的数据不符合easyui树形展示的数据格式
* 需要转化成easyui所能识别的数据格式
*
* @param map
* @param treeNode
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
//流程:第四步
private void menu2TreeNode(Map<String, Object> map,TreeNode treeNode) throws InstantiationException, IllegalAccessException, SQLException{
treeNode.setId(map.get("Menuid").toString() ); //单个的赋值
treeNode.setName(map.get("Menuname").toString());
treeNode.setAttributes(map);
//treeNode.setChildren(children);
Map<String, String[]> jspMap = new HashMap<>();//给参数集合实例化
jspMap.put("id", new String[] {treeNode.getId()});//给参数中加入一个id的参数
List<Map<String, Object>> listMenu = this.listMenu(jspMap, null); // 重点!!! 如果第二次查询没有这个id的话就结束,否则 二,三,四流程继续
List<TreeNode> treeNodeList = new ArrayList<>(); //用一个List<TreeNode>集合准备装着子节点的所有东西
menuList2TreeNodeList(listMenu, treeNodeList); //如果有的话就继续运行,否则不运行
treeNode.setChildren(treeNodeList); //将treeNode的children属性赋值
}
//流程:第三步
private void menuList2TreeNodeList(List<Map<String, Object>> mapList,List<TreeNode> treeNodeList) throws InstantiationException, IllegalAccessException, SQLException{
TreeNode treeNode = null; //准备最后放入集合内部TreeNode
for (Map<String, Object> map : mapList) {//遍历List<Menu>中然后两者相互转换。因为最后的结果就是List<TreeNode>
treeNode = new TreeNode();
menu2TreeNode(map, treeNode);//调用到第一流程中的最后一步:为TreeNode设值
treeNodeList.add(treeNode);//将转换完成的加入到treeNode
}
}
}
userDao
package com.liwangwang.crud.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.liwangwang.crud.util.JsonBaseDao;
import com.liwangwang.crud.util.JsonUtils;
import com.liwangwang.crud.util.PageBean;
import com.liwangwang.crud.util.StringUtils;
public class UserDao extends JsonBaseDao{
//获取哦用户信息
public List<Map<String,Object>> list(Map<String, String[]> pamap ,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_easyui_user_version2 where true ";
String uname = JsonUtils.getParamVal(pamap, "uname");
String uid = JsonUtils.getParamVal(pamap, "uid");//获取参数值uid
String upwd = JsonUtils.getParamVal(pamap, "upwd");//获取参数值upwd
if(StringUtils.isNotBlank(uid)) {
sql += " and uid = "+uid;
}
if(StringUtils.isNotBlank(upwd)) {
sql +=" and upwd = "+upwd;
}
if(StringUtils.isNotBlank(uname)) {
sql +=" and uname like '%"+uname+"%' ";
}
return super.executeQuery(sql, pageBean);
}
//获取菜单所有
public List<Map<String,Object>> listmenu(Map<String, String[]> pamap ,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_easyui_usermenu where true ";
String uid = JsonUtils.getParamVal(pamap, "uid");
if(StringUtils.isNotBlank(uid)) {
sql += " and uid = "+uid;
}
return super.executeQuery(sql, pageBean);
}
//修改
public int edit(Map<String, String[]> pamap ) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql = "update t_easyui_user_version2 set uid = ?,uname=?,upwd=? where serialno = ?";
return super.executeUpdate(sql,new String[] {"uid","uname","upwd","SerialNo"}, pamap);
}
//增加
public int add(Map<String, String[]> pamap ) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql = "insert into t_easyui_user_version2(SerialNo,uid,uname,upwd) values('"+JsonUtils.getParamVal(pamap, "uid")+1+"',?,?,?) ";
return super.executeUpdate(sql,new String[] {"uid","uname","upwd"}, pamap);
}
//删除
public int del(Map<String, String[]> pamap ) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql = "delete from t_easyui_user_version2 where SerialNo = ?";
return super.executeUpdate(sql,new String[] {"SerialNo"}, pamap);
}
}
entity
TreeNode
package com.liwangwang.crud.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TreeNode {
private String id;
private String name;
private Map<String, Object> attributes = new HashMap<>();
private List<TreeNode> children = new ArrayList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
public TreeNode(String id, String text, Map<String, Object> attributes, List<TreeNode> children) {
super();
this.id = id;
this.name = name;
this.attributes = attributes;
this.children = children;
}
public TreeNode() {
super();
}
@Override
public String toString() {
return "TreeNode [id=" + id + ", name=" + name + ", attributes=" + attributes + ", children=" + children + "]";
}
}
web
BaseAction
package com.liwangwang.crud.web;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
/**
* 每一个开发的子控制器要用的属性都定义在通用的action中。
* @author Administrator
*
*/
public class BaseAction implements ServletRequestAware, ServletResponseAware{
/**
* 为了传值使用
*/
protected HttpServletResponse response;
protected HttpServletRequest request;
protected HttpSession session;
protected ServletContext application;
/**
* 为了配置跳转页面所用
*/
protected final static String SUCCESS = "success";
protected final static String FAIL = "fail";
protected final static String LIST = "list";
protected final static String ADD = "add";
protected final static String EDIT = "edit";
protected final static String DETAIL = "detail";
/**
* 具体传值字段 后端向jsp页面传值所用字段
*/
protected Object result;
protected Object msg;
protected int code;
public Object getResult() {
return result;
}
public Object getMsg() {
return msg;
}
public int getCode() {
return code;
}
@Override
public void setServletResponse(HttpServletResponse arg0) {
this.response = arg0;
}
@Override
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
this.session = arg0.getSession();
this.application = arg0.getServletContext();
}
}
UserAction
package com.liwangwang.crud.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liwangwang.crud.dao.UserDao;
import com.liwangwang.crud.util.PageBean;
import com.liwangwang.crud.util.ResponseUtil;
public class UserAction extends BaseAction{
private UserDao ud = new UserDao();
public String login() {
try {
List<Map<String, Object>> list = ud.list(request.getParameterMap(), null);//获取数据库中有无这个人
if(list!=null&&list.size()>0) {//如果有,则进入下一步
List<Map<String, Object>> listmenu = ud.listmenu(request.getParameterMap(), null);//获取这个人的权限
StringBuilder sb = new StringBuilder();
for (Map<String, Object> map : listmenu) {//将权限已字符串的形式打包
sb.append(","+map.get("menuId"));
}
request.setAttribute("menuHid", sb.substring(1));//设置到request中
}else {
return "login";//如果没有就到login.jsp中
}
} catch (Exception e) {
e.printStackTrace();
}
return "index";//如果有这个人就到index.jsp中
}
public String editlist() {
try {
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
List<Map<String, Object>> list = this.ud.list(request.getParameterMap(), pageBean);
ObjectMapper om =new ObjectMapper();
Map<String, Object> map=new HashMap<>();
map.put("code", 0);
map.put("count", pageBean.getTotal());
map.put("data", list);
ResponseUtil.write(response, om.writeValueAsString(map));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String adduser() {
try {
int n = ud.add(request.getParameterMap());
ResponseUtil.write(response, n);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String edituser() {
try {
int n = ud.edit(request.getParameterMap());
ResponseUtil.write(response, n);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String deluser() {
try {
int n = ud.del(request.getParameterMap());
ResponseUtil.write(response, n);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
MenuAction
package com.liwangwang.crud.web;
import java.sql.SQLException;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liwangwang.crud.dao.MenuDao;
import com.liwangwang.crud.entity.TreeNode;
import com.liwangwang.crud.util.ResponseUtil;
public class MenuAction extends BaseAction {
private MenuDao menuDao = new MenuDao();
public String treeMenu() {
try {
List<TreeNode> list = this.menuDao.list(request.getParameterMap(), null);
ObjectMapper om = new ObjectMapper();
//将list集合转换成json串
String jsonStr = om.writeValueAsString(list);
ResponseUtil.write(response, jsonStr);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
util
PageBean
package com.liwangwang.crud.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 行数/页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 默认分页
private String url;// 上一次请求的地址
private Map<String, String[]> parameterMap;// 上一次请求的所有参数
public PageBean() {
super();
}
/**
* 对分页bean进行初始化
*
* @param request
*/
public void setRequest(HttpServletRequest request) {
// 公共参数
this.setPage(request.getParameter("page"));
this.setRows(request.getParameter("limit"));
this.setPagination(request.getParameter("pagination"));
// 请求地址和请求参数
this.setUrl(request.getContextPath() + request.getServletPath());
this.setParameterMap(request.getParameterMap());
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if (null != page && !"".equals(page.trim())) {
this.page = Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
if (null != rows && !"".equals(rows.trim())) {
this.rows = Integer.parseInt(rows);
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if ("false".equals(pagination)) {
this.pagination = false;
}
}
/**
* 下一页
*
* @return
*/
public int getNextPage() {
int nextPage = page + 1;
if (nextPage > this.getMaxPage()) {
nextPage = this.getMaxPage();
}
return nextPage;
}
/**
* 上一页
*
* @return
*/
public int getPreviousPage() {
int previousPage = page - 1;
if (previousPage < 1) {
previousPage = 1;
}
return previousPage;
}
/**
* 最大页码
*
* @return
*/
public int getMaxPage() {
return total % rows == 0 ? total / rows : total / rows + 1;
}
/**
* 起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (page - 1) * rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
JsonUtil
package com.liwangwang.crud.util;
import java.util.Arrays;
import java.util.Map;
/**
* 专门用来处理json数据的工具包
* @author Administrator
*
*/
public class JsonUtils {
/**
* 从paramMap拿到咱们所需要用到的查询维度,用于sql语句拼接
* @param paramMap 获取从jsp页面传递到后台的参数集合(req.getParamterMap)
* @param key
* @return
*/
public static String getParamVal(Map<String,String[]> paramMap, String key) {
if(paramMap != null && paramMap.size()>0) {
String[] vals = paramMap.get(key);
if(vals != null && vals.length > 0) {
String val = Arrays.toString(vals);
return val.substring(1, val.length()-1);
}
return "";
}
return "";
}
}
ResponseUtil
package com.liwangwang.crud.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
public class ResponseUtil {
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}
StringUtils
package com.liwangwang.crud.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
BeanDao
package com.liwangwang.crud.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 通用的查询方法 23种设计模式之策略模式
* 作用:在方法或类中已经完成了对应的功能,然后在调用方去根据自己的需求去处理结果。 使得代码更加灵活。
*
* @author Administrator
*
* @param <T>
*/
public class BeanDao<T> {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public List<T> executeQuery(String sql ,Class clz ,PageBean page ){
List<T> lt = new ArrayList<>();
try {
con = DBAccess.getConnection(); //连接三部曲
if(page!=null&&page.isPagination()) {//要进行分页的进这里
String countPage = countPage(sql);//获取这个类在数据库的总行数
pst = con.prepareStatement(countPage);
rs = pst.executeQuery();
if(rs.next()) {
page.setTotal(rs.getLong(1)+"");
}
String getPage = getPage(sql,page);//获取这个页面的页数
pst = con.prepareStatement(getPage);
rs = pst.executeQuery();
}
else {
pst = con.prepareStatement(sql);//连接三部曲
rs = pst.executeQuery(); //连接三部曲
}
while (rs.next()) {
T t = (T) clz.newInstance();//将传过来的class文件实列化,类型为实现本类的T参数
Field[] fields = clz.getDeclaredFields();//获取这个类里的所有属性
for (Field field : fields) { //遍历
System.out.println(field.getName()+":"+rs.getObject(field.getName()));
field.setAccessible(true); //打开权限
field.set(t, rs.getObject(field.getName()));
}
System.out.println(t.toString());
lt.add(t);//加入到集合内部
}
} 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();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
DBAccess.close(con, pst, rs);
}
return lt;
}
//增 ,删,改
public int executeUpdate(String sql ,String [] attrs ,T t ){
int n = 0;
try {
con = DBAccess.getConnection(); //连接三部曲
pst = con.prepareStatement(sql); //连接三部曲
for (int i = 0; i < attrs.length; i++) {
Field Field = t.getClass().getDeclaredField(attrs[i]);
Field.setAccessible(true);
pst.setObject(i+1, Field.get(t));
}
n= pst.executeUpdate();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
}
finally {
DBAccess.close(con, pst, rs);
}
return n;
}
private String getPage(String sql, PageBean page) {
return sql+" limit "+page.getStartIndex()+","+page.getRows();
}
private String countPage(String sql) {
return "select count(1) from ( "+sql+" ) t";
}
}
上一篇: LayUI之多选下拉框
推荐阅读