layui二级权限和增删改查
先给大家简单介绍一下layui:
是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。
layer是一款近年来备受青睐的web弹层组件,她具备全方位的解决方案,致力于服务各水平段的开发人员,您的页面会轻松地拥有丰富友好的操作体验。
在与同类组件的比较中,layer总是能轻易获胜。她尽可能地在以更少的代码展现更强健的功能,且格外注重性能的提升、易用和实用性,正因如此,越来越多的开发者将媚眼投上了layer(已被9496411人次关注)。layer 甚至兼容了包括 IE6 在内的所有主流浏览器。她数量可观的接口,使得您可以自定义太多您需要的风格,每一种弹层模式各具特色,广受欢迎。当然,这种“王婆卖瓜”的陈述听起来总是有点难受,因此你需要进一步了解她是否真的如你所愿。
layer 采用 MIT 开源许可证,将会永久性提供无偿服务。因着数年的坚持维护,截至到2017年9月13日,已运用在超过 30万 家 Web 平台,其中不乏众多知名大型网站。目前 layer 已经成为国内乃至全世界最多人使用的 Web 弹层解决方案,并且她仍在与 Layui 一并高速发展。
下载网站我这有一个:layui的下载(仅共参考)
首先写实体类:
TreeNode:
package com.lihao.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 title;
private boolean spread=true;//设置节点默认打开
private List<TreeNode> children=new ArrayList<>();
private Map<String, Object> attributes=new HashMap<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSpread() {
return spread;
}
public void setSpread(boolean spread) {
this.spread = spread;
}
public TreeNode() {
super();
}
}
然后写dao方法:
MenuDao:
package com.lihao.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lihao.entity.TreeNode;
import com.lihao.util.JsonBaseDao;
import com.lihao.util.JsonUtils;
import com.lihao.util.PageBean;
import com.lihao.util.StringUtils;
public class MenuDao extends JsonBaseDao {
/**
*
* @param map req.getParameterMap
* @param pageBean 分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
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> treeNodeList=new ArrayList<>();
menuList2TreeNodeList(listMenu, treeNodeList);
return treeNodeList;
}
/**
* 根据传入的id找到它所对应的菜单,然后再由这些菜单成为最大节点依次找到下面的子节点
* @param map
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Map<String, Object>> listMenuSef(Map<String, String[]> map,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from tb_menu where true";
String id=JsonUtils.getParamVal(map, "menuHid");
if(StringUtils.isNotBlank(id)) {
sql+=" and menuid in ("+id+") ";
}
else {
sql+=" and menuid=-1";
}
return super.executeQuery(sql, pageBean);
}
/**
* 1、查询menu表的数据
* @param map
* @param pageBean
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<Map<String, Object>> listMenu(Map<String, String[]> map,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from tb_menu where true ";
String id=JsonUtils.getParamVal(map, "id");
if(StringUtils.isNotBlank(id)) {
sql+=" and parentid = "+id;
}
else {
sql+=" and parentid = -1";
}
return super.executeQuery(sql, pageBean);
}
/**
* menu表的数据不符合easyui树形展示的数据格式
* 需要转换成easyui所能识别的数据格式
* @param map
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void menu2TreeNode(Map<String, Object> map,TreeNode treeNode) throws InstantiationException, IllegalAccessException, SQLException {
treeNode.setId(map.get("menuid").toString());
treeNode.setTitle(map.get("menuname").toString());
treeNode.setAttributes(map);
Map<String, String[]> jspMap=new HashMap<>();
//获取到了当前节点的Id
jspMap.put("id", new String [] {treeNode.getId()});
// 调方法把id当成parentid来查询子节点
List<Map<String, Object>> listMenu = this.listMenu(jspMap, null);
List<TreeNode> treeNodeList=new ArrayList<>();
menuList2TreeNodeList(listMenu, treeNodeList);
treeNode.setChildren(treeNodeList);
}
/**
* 转化数据格式
* @param mapList
* @param treeNodeList
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public void menuList2TreeNodeList(List<Map<String, Object>> mapList,List<TreeNode> treeNodeList) throws InstantiationException, IllegalAccessException, SQLException {
TreeNode treeNode=null;
for (Map<String, Object> map : mapList) {
treeNode=new TreeNode();
menu2TreeNode(map, treeNode);
treeNodeList.add(treeNode);
}
}
}
BookDao:
package com.lihao.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.lihao.util.JsonBaseDao;
import com.lihao.util.JsonUtils;
import com.lihao.util.PageBean;
import com.lihao.util.StringUtils;
public class BookDao extends JsonBaseDao {
/**
* 查所有
* @param paMap
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Map<String, Object>> list(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from t_mvc_book where true ";
String bname = JsonUtils.getParamVal(paMap, "bname");
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%'";
}
return super.executeQuery(sql, pageBean);
}
/**
* 增加
* @param paMap
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int add(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="insert into t_mvc_book(bid,bname,price) values(?,?,?)";
return super.executeUpdate(sql, new String[] {"bid","bname","price"}, paMap);
}
public int del(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, new String[] {"bid"}, paMap);
}
public int edit(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","price","bid"}, paMap);
}
}
UserDao:
package com.lihao.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lihao.util.JsonBaseDao;
import com.lihao.util.JsonUtils;
import com.lihao.util.PageBean;
import com.lihao.util.StringUtils;
public class UserDao extends JsonBaseDao {
/**
* 登录查询用户表
* @param paMap
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Map<String, Object>> list(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from tb_user where true";
String uid=JsonUtils.getParamVal(paMap, "uid");
String upwd=JsonUtils.getParamVal(paMap, "upwd");
if(StringUtils.isNotBlank(uid)) {
sql+=" and uid="+uid;
}
if(StringUtils.isNotBlank(upwd)) {
sql+=" and upwd="+upwd;
}
return super.executeQuery(sql, pageBean);
}
/**
* 通过中间表查询登录用户所对应的权限
* @param paMap
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Map<String, Object>> listMenu(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from tb_usermenu where true";
String uid = JsonUtils.getParamVal(paMap, "uid");
if(StringUtils.isNotBlank(uid)) {
sql+=" and uid="+uid;
}
return super.executeQuery(sql, pageBean);
}
}
然后写web包
BookAction:
package com.lihao.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.lihao.dao.BookDao;
import com.lihao.util.JsonUtils;
import com.lihao.util.PageBean;
import com.lihao.util.ResponseUtil;
import com.lihao.framework.ActionSupport;
public class BookAction extends ActionSupport {
private BookDao bookDao=new BookDao();
public String list(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Map<String, Object>> list = this.bookDao.list(req.getParameterMap(),pageBean);
Map map=new HashMap();
map.put("data", list);
map.put("code", 0);
map.put("count", pageBean.getTotal());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(map));
return null;
}
public int addBook(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
int add = bookDao.add(req.getParameterMap());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(add));
return add;
}
public int del(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
int del = bookDao.del(req.getParameterMap());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(del));
return del;
}
public int edit(HttpServletRequest req,HttpServletResponse resp) throws JsonProcessingException, Exception {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("html/text;charset=utf-8");
int edit = bookDao.edit(req.getParameterMap());
ObjectMapper om=new ObjectMapper();
ResponseUtil.write(resp, om.writeValueAsString(edit));
return edit;
}
}
UserAction:
package com.lihao.web;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lihao.dao.UserDao;
import com.lihao.util.PageBean;
import com.lihao.util.ResponseUtil;
import com.lihao.framework.ActionSupport;
public class UserAction extends ActionSupport{
private UserDao userDao=new UserDao();
public String login(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException {
List<Map<String, Object>> list=this.userDao.list(req.getParameterMap(), null);
if(list!=null&&list.size()>0) {
List<Map<String, Object>> listMenu = this.userDao.listMenu(req.getParameterMap(), null);
StringBuffer sb=new StringBuffer();
for (Map<String, Object> map : listMenu) {
sb.append(","+map.get("menuId"));
}
req.setAttribute("menuHid", sb.substring(1));
}
else {
return "login";
}
return "index";
}
}
MenuAction:
package com.lihao.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.lihao.dao.MenuDao;
import com.lihao.entity.TreeNode;
import com.lihao.util.ResponseUtil;
import com.lihao.framework.ActionSupport;
public class MenuAction extends ActionSupport {
private MenuDao menuDao=new MenuDao();
public String treeMenu(HttpServletRequest req,HttpServletResponse resp) throws Exception {
List<TreeNode> list = this.menuDao.list(req.getParameterMap(), null);
ObjectMapper om=new ObjectMapper();
// 将List集合转为json串
String jsonStr = om.writeValueAsString(list);
ResponseUtil.write(resp, jsonStr);
return null;
}
}
接下来写Util包:
BaseAction:
package com.lihao.util;
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();
}
}
BaseDao:
package com.lihao.util;
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 BaseDao<T> {
// $.ajax
protected interface Callback<T> {
public List<T> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException;
}
public List<T> executeQuery(String sql, PageBean pageBean, Callback<T> callback)
throws SQLException, InstantiationException, IllegalAccessException {
if (pageBean != null && pageBean.isPagination()) {
Connection con = DBAccess.getConnection();
String countSql = getCountSql(sql);
PreparedStatement countPst = con.prepareStatement(countSql);
ResultSet countRs = countPst.executeQuery();
if (countRs.next()) {
pageBean.setTotal(countRs.getObject(1).toString());
}
DBAccess.close(null, countPst, countRs);
String pageSql = getPageSql(sql, pageBean);
PreparedStatement pagePst = con.prepareStatement(pageSql);
ResultSet pageRs = pagePst.executeQuery();
try {
return callback.foreach(pageRs);
} finally {
DBAccess.close(con);
}
} else {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
try {
return callback.foreach(rs);
} finally {
DBAccess.close(con);
}
}
}
/**
* 将原生态的sql语句转换成查对应的当页记录数sql语句
*
* @param sql
* @param pageBean
* @return
*/
private String getPageSql(String sql, PageBean pageBean) {
return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
}
/**
* 将原生态的sql语句转换成查总记录输的sql语句
*
* @param sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from (" + sql + " ) t";
}
}
DBAccess:
package com.lihao.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
EncodingFiter:
package com.lihao.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
JsonBase:
package com.lihao.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonBaseDao extends BaseDao<Map<String,Object>> {
public List<Map<String,Object>> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
return super.executeQuery(sql, pageBean, new Callback<Map<String,Object>>() {
@Override
public List<Map<String,Object>> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException {
/*
* 1、创建一个实体类的实例
* 2、给创建的实例属性赋值
* 3、将添加完类容的实体类添加到list集合中
*/
// list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
List<Map<String,Object>> list = new ArrayList<>();
// 获取源数据
ResultSetMetaData md = rs.getMetaData();
int count = md.getColumnCount();
Map<String,Object> map = null;
while(rs.next()) {
map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(md.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
return list;
}
});
}
/**
*
* @param sql
* @param attrs map中的key
* @param paMap jsp向后台传递的参数集合
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int executeUpdate(String sql, String[] attrs, Map<String,String[]> paMap) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
for (int i = 0; i < attrs.length; i++) {
pst.setObject(i+1, JsonUtils.getParamVal(paMap, attrs[i]));
}
return pst.executeUpdate();
}
}
JsonUtil:
package com.lihao.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 "";
}
}
PageBean:
package com.lihao.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 Map<String, String[]> parameterMap;
// 获取上一次访问后台的url
private String url;
/**
* 初始化pagebean
*
* @param req
*/
public void setRequest(HttpServletRequest req) {
this.setPage(req.getParameter("page"));
this.setRows(req.getParameter("rows"));
// 只有jsp页面上填写pagination=false才是不分页
this.setPagination(!"fasle".equals(req.getParameter("pagination")));
this.setParameterMap(req.getParameterMap());
this.setUrl(req.getRequestURL().toString());
}
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
}
public int nextPage() {
return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
}
public int previousPage() {
return this.page > 1 ? this.page - 1 : 1;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(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 Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
+ ", parameterMap=" + parameterMap + ", url=" + url + "]";
}
}
ResponseUtil:
package com.lihao.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();
}
}
StringUtil:
package com.lihao.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);
}
}
config.properties:
#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql5
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_123?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
然后配置mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/BookAction" type="com.lihao.web.BookAction">
<forward name="index" path="/index.jsp" redirect="false"></forward>
</action>
<action path="/MenuAction" type="com.lihao.web.MenuAction">
<forward name="index" path="/index.jsp" redirect="false"></forward>
</action>
<action path="/UserAction" type="com.lihao.web.UserAction">
<forward name="index" path="/jsp/index.jsp" redirect="false"></forward>
<forward name="login" path="/jsp/login.jsp" redirect="false"></forward>
</action>
</config>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Layui</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.lihao.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.lihao.framework.ActionServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
然后是jsp界面
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="layui/css/layui.css">
<style type="text/css">
.container{
width: 420px;
height: 320px;
min-height: 320px;
max-height: 320px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
padding: 20px;
z-index: 130;
border-radius: 8px;
background-color: #fff;
box-shadow: 0 3px 18px rgba(100, 0, 0, .5);
font-size: 16px;
}
.close{
background-color: white;
border: none;
font-size: 18px;
margin-left: 410px;
margin-top: -10px;
}
.layui-input{
border-radius: 5px;
width: 300px;
height: 40px;
font-size: 15px;
}
.layui-form-item{
margin-left: -20px;
}
#logoid{
margin-top: -16px;
padding-left:150px;
padding-bottom: 15px;
}
.layui-btn{
margin-left: -50px;
border-radius: 5px;
width: 350px;
height: 40px;
font-size: 15px;
}
.verity{
width: 120px;
}
.font-set{
font-size: 13px;
text-decoration: none;
margin-left: 120px;
}
a:hover{
text-decoration: underline;
}
</style>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/layui/css/layui.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/layui/layui.js"></script>
</head>
<body>
<form class="layui-form" action="${pageContext.request.contextPath}/UserAction.action?methodName=login" method="post">
<div class="container">
<h2 align="center">用户登录</h2>
<div class="layui-form-mid layui-word-aux" >
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="uid" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密 码</label>
<div class="layui-input-block">
<input type="password" name="pwd" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
<!-- <div class="layui-form-mid layui-word-aux">辅助文字</div> -->
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<input class="layui-btn" lay-submit lay-filter="formDemo" type="submit" value="登录" />
</div>
</div>
</div>
</form>
<script type="text/javascript" src="layui/layui.js"></script>
<script>
layui.use(['form', 'layedit', 'laydate'], function(){
var form = layui.form
,layer = layui.layer
,layedit = layui.layedit
,laydate = layui.laydate;
//监听提交
form.on('submit(demo1)', function(data){
layer.alert(JSON.stringify(data.field), {
title: '最终的提交信息'
})
return false;
});
});
</script>
</body>
</html>
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>
<style type="text/css">
.test{
color: white;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/layui/css/layui.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/layui/layui.js"></script>
<script type="text/javascript">
//数据表格
layui.use(['table','layer','form','tree'], function(){
var table = layui.table;
var layer=layui.layer;
var form=layui.form;
var tree = layui.tree;
var $=layui.$;
var url=$("#ctx").val();
table.render({
elem: '#demo'
,url:'${pageContext.request.contextPath}/BookAction.action?methodName=list'
,method:'post'
,page:true
,cols: [[
{type:'checkbox',fixed:'left'}
,{field:'bid', title: 'ID' ,sort: true}
,{field:'bname', title: '书名'}
,{field:'price', title: '价格'}
,{field:'right', title: '操作', width:250,toolbar:"#barDemo"}
]]
});
//增加按钮
$("#add").click(function(){
layer.open({
type: 1,
title:"新增",
area:['50%','50%'],
btn: ['确定', '取消'],
content: $("#window"),
yes:function(index,layero){
$.getJSON(url+'/BookAction.action?methodName=addBook',{
bid: $('#bid').val(),
bname: $('#bname').val(),
price: $('#price').val()
},function(data){
//根据后台返回的参数,来进行判断
if(data>0){
layer.alert('增加成功',{icon:1,title:'提示'},function(i){
layer.close(i);
layer.close(index);//关闭弹出层
$("#book")[0].reset()//重置form
})
table.reload('demo',{//重载表格
page:{
curr:1
}
})
}
});
}
});
})
$('#search').on('click', function () {
// 搜索条件
var name = $('#name').val();
table.reload('demo', {
method: 'post'
, where: {
'bname': name
}
, page: {
curr: 1
}
});
});
//获取按钮
table.on('tool(test)', function(obj){
var data = obj.data; //获得当前行数据
var tr=obj.tr//活动当前行tr 的 DOM对象
if(obj.event === 'del'){ //删除
layer.confirm('确定删除吗?',{title:'删除'}, function(index){
//向服务端发送删除指令og
$.getJSON(url+'/BookAction.action?methodName=del',{bid:data.bid}, function(ret){
layer.close(index);//关闭弹窗
table.reload('demo', {//重载表格
})
});
layer.close(index);
});
} else if(obj.event === '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:$("#window") //弹窗路径
,success:function(layero,index){
$('#bid').val(data.bid);
$('#bname').val(data.bname);
$('#price').val(data.price);
},yes:function(index,layero){
$.getJSON(url+'/BookAction.action?methodName=edit',{
bid: data.bid,
bid: $('#bid').val(),
bname: $('#bname').val(),
price: $('#price').val()
},function(data){
//根据后台返回的参数,来进行判断
if(data>0){
layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
layer.close(i);
layer.close(index);//关闭弹出层
$("#book")[0].reset()//重置form
})
table.reload('demo',{//重载表格
page:{
curr:1
}
})
}
});
}
});
}
});
$.ajax({
type: "post",
url: url+"/MenuAction.action?methodName=treeMenu&&menuHid="+$("#menuHid").val(),
dataType: 'json',
success: function (data) {
tree.render({
elem: '#test'
,data: data
,showLine: false //是否开启连接线
,click: function (node) {
console.log(node) //node即为当前点击的节点数据
}
});
}
})
})
</script>
<title>layui</title>
</head>
<body class="layui-layout-body">
<div class="site-text" style="margin: 5%; display: none" id="window">
<form class="layui-form" id="book" method="post" lay-filter="example">
<div class="layui-form-item">
<label class="layui-form-label">书本编号</label>
<div class="layui-input-block">
<input type="text" id="bid" name="bid" lay-verify="title" autocomplete="off" placeholder="请输入编号" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">书本名称</label>
<div class="layui-input-block">
<input type="text" id="bname" name="bname" lay-verify="title" autocomplete="off" placeholder="请输入名称" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">书本价格</label>
<div class="layui-input-block">
<input type="text" id="price" name="price" lay-verify="title" autocomplete="off" placeholder="请输入价格" class="layui-input">
</div>
</div>
</form>
</div>
<input type="hidden" id="ctx" value="${pageContext.request.contextPath }" />
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-logo">后台</div>
<!-- 头部区域(可配合layui已有的水平导航) -->
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item">
<a href="javascript:;">其它系统</a>
<dl class="layui-nav-child">
<dd><a href="">邮件管理</a></dd>
<dd><a href="">消息管理</a></dd>
<dd><a href="">授权管理</a></dd>
</dl>
</li>
</ul>
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item">
<a href="javascript:;">
<img src="http://t.cn/RCzsdCq" class="layui-nav-img">
欢迎来到本系统
</a>
<dl class="layui-nav-child">
<dd><a href="">基本资料</a></dd>
<dd><a href="">安全设置</a></dd>
</dl>
</li>
<li class="layui-nav-item"><a href="">退了</a></li>
</ul>
</div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll">
<!-- 左侧导航区域(可配合layui已有的垂直导航) -->
<div id="test" class="demo-tree-more"></div>
</div>
</div>
<input type="hidden" id="menuHid" value="${menuHid}" />
<div class="layui-body">
<!-- 内容主体区域 -->
<div style="padding: 15px;">
<div class="layui-inline">
书名:
<div class="layui-inline">
<input class="layui-input" id="name" name="name" autocomplete="off" />
</div>
<button id="search" class="layui-btn" lay-submit="" lay-filter="search">搜索</button>
<button id="add" class="layui-btn" lay-submit="" lay-filter="pageSubmit" >新增</button>
</div>
<table id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>
</script>
</div>
</div>
<div class="layui-footer">
<!-- 底部固定区域 -->
© layui.com - 底部固定区域
</div>
</div>
</body>
</html>
最后我要说一下MVC所要用到的jar包