
首先认识layui
layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发。
(推荐教程:layui)
下载之后导进css、js样式
简单的效果图

接下来直接上代码
dao方法
package com.chen.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.chen.util.JsonBaseDao;
import com.chen.util.JsonUtils;
import com.chen.util.PageBean;
import com.chen.util.StringUtils;
public class BooktypeDao extends JsonBaseDao{
/**
* 书籍类别查询
* @param paMap
* @param pageBean
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<map>> list(Map<string> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql=" select * from t_type where true";
String tid=JsonUtils.getParamVal(paMap, "tid");
String tname=JsonUtils.getParamVal(paMap, "tname");
if(StringUtils.isNotBlank(tid)) {
sql+=" and tid ="+tid+" ";
}
if(StringUtils.isNotBlank(tname)) {
sql+=" and tname like '%"+tname+"%'";
}
sql += " order by tid desc ";
return executeQuery(sql, pageBean);
}
/**
* 增加
* @param paMap
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int addType(Map<string> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="insert into t_type(tname) values(?) ";
return super.executeUpdate(sql, new String[] {"tname"}, paMap);
}
/**
* 修改
* @param paMap
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int editType(Map<string> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="update t_type set tname=? where tid=?";
return super.executeUpdate(sql, new String[] {"tname","tid"}, paMap);
}
/**
* 删除
* @param paMap
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int removeType(Map<string> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="delete from t_type where tid=? ";
return super.executeUpdate(sql, new String[] {"tid"}, paMap);
}
}</string></string></string></string></map>
entity一个树形的实体类
package com.chen.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> 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> getAttributes() {
return attributes;
}
public void setAttributes(Map<string> 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> 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 + "]";
}
}</treenode></string></treenode></treenode></string></string></treenode></string>
action子控制器
package com.liuting.web;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.chen.dao.BooktypeDao;
import com.chen.framework.ActionSupport;
import com.chen.util.PageBean;
import com.chen.util.ResponseUtil;
public class BooktypeAction extends ActionSupport {
private BooktypeDao booktypeDao=new BooktypeDao();
/**
* 查询书籍类别
* @param req
* @param resp
* @return
* @throws Exception
*/
public String list(HttpServletRequest req,HttpServletResponse resp) throws Exception {
try {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<map>> list = this.booktypeDao.list(req.getParameterMap(), pageBean);
ObjectMapper om =new ObjectMapper();
Map<string> map=new HashMap();
map.put("code", 0);
map.put("count", pageBean.getTotal());
map.put("data", list);
ResponseUtil.write(resp, om.writeValueAsString(map));
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
/**
* 增加
* @param req
* @param resp
* @return
*/
public String addBookType(HttpServletRequest req,HttpServletResponse resp) {
try {
List<map>> list = this.booktypeDao.list(req.getParameterMap(), null);
int val = 0;
//如果集合不为空 或者长度等于 0 就把它增加进去
if(list==null || list.size() == 0) {
val = this.booktypeDao.addType(req.getParameterMap());
}
else {
val= 2;
}
ResponseUtil.write(resp, val);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 删除书本类别
* @throws Exception
* @throws JsonProcessingException
*
*/
public String deleteBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
try {
int deleteBookType=this.booktypeDao.removeType(req.getParameterMap());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(deleteBookType));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
/**
* 修改书籍类别
* @param req
* @param resp
* @return
* @throws JsonProcessingException
* @throws Exception
*/
public String updateBookType(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
try {
int updateBookType=this.booktypeDao.editType(req.getParameterMap());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(updateBookType));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
/**
* 下拉框
*/
public String listSelect(HttpServletRequest req,HttpServletResponse resp) throws Exception {
try {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<map>> list = this.booktypeDao.list(req.getParameterMap(), pageBean);
ObjectMapper om =new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(list));
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
}</map></map></string></map>
mvc.xml的配置路径
<?xml version="1.0" encoding="UTF-8"?><config><action><forward></forward><forward></forward></action><action><forward></forward></action><action><forward></forward></action><!--书本信息 --><action><forward></forward><forward></forward></action></config>
web.xml的配置路径
<?xml version="1.0" encoding="UTF-8"?><web-app>
<display-name>Mvc_Layui</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.chen.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatherServlet</servlet-name>
<servlet-class>com.chen.framework.DispatherServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping></web-app>
jsp页面
<meta><title>Insert title here</title><div>
<span>
<a>书籍类别管理</a>
<a><cite>分类列表</cite></a>
</span>
</div>
<blockquote>
<!--搜索维度 -->
<div>
<div>
<label>书籍名称</label>
<div>
<input>
</div>
<button><i></i>查询</button>
<button>新建</button>
</div>
</div>
</blockquote>
<!--隐藏域传值 -->
<input><!--根据table id 来展示表格数据 -->
<script>
<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon">编辑
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除
</script>
<script>
//管理
//执行渲染
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+'/booktypeAction.action?methodName=list'//所对应调用的接口
,method:'post' //提交方式
,cols:[[
/*根据数据库的表格所对应的名称 */
{field:'tid',height:80, width:300, title: '书籍类别序号', sort: true}
,{field:'tname', height:80,width:300, title: '书籍类别名称'}
,{field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作栏
]]
,page:'true'//分页
, id: 'testReload'
});
//上方菜单操作栏(查询、以及 增加 按钮 )
var $ = layui.$, active = {
//查询
reload: function () {
var booktypename = $('#booktypename');//书籍类别名称 根据 id来取值
console.log(booktypename.val());
// 执行重载
table.reload('testReload', {
page: {
curr: 1
// 重新从第 1 页开始
},
where: {
key: 'tname',
tname: booktypename.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+"/booktypeAction.action?methodName=addBookType", {
tname: $("#booktypename1").val(), ///角色名
/* booktypename: $("input[ name='booktypename1']").val(), *///角色名
}, function (data) {
/*根据后台返回的参数来进行判断 */
if (data==1) {
layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
layer.close(i);
layer.close(index);//关闭弹出层
$("#booktype")[0].reset()//重置form
})
table.reload('testReload', {//重载表格
page: {
curr: 1
// 重新从第 1 页开始
}
})
} else if(data==2){
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+'/booktypeAction.action?methodName=deleteBookType',{tid:data.tid}, function(ret){
layer.close(index);//关闭弹窗
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){
$('#booktypeid').val(data.tid);
$('#booktypename1').val(data.tname);
},yes:function(index,layero){
/* $.ajaxSettings.async = false; */
$.getJSON(urlex+'/booktypeAction.action?methodName=updateBookType',{
tid: $('#booktypeid').val(),
tname: $('#booktypename1').val(),
tid: data.tid,
},function(data){
//根据后台返回的参数,来进行判断
if(data>0){
layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
layer.close(i);
layer.close(index);//关闭弹出层
$("#booktype")[0].reset()//重置form
})
table.reload('testReload',{//重载表格
page:{
curr:1
}
})
}
});
}
});
}
});
});
// 实现查询所有的菜单
</script>
本次所用到的jar包

index.js
$(function () {
$.ajax({
type: "post",
url: "menuAction.action?methodName=treeMenu",
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></iframe>'// 支持传入html
,
// width="99%" height="99%"
id: node.id
});
element.tabChange('tabs', node.id);
}
}
}
});
}
});
})
完成!