easyui增删改查

文章目录

  • 一.前言
    • 1.1前后端分离
    • 1.2easyui的crud(dialog,datagrid、form讲解)
    • 1.3 下载软件及相关jar包
    • 1.4引入jar包
  • 二.案例:

一.前言

Easyui是非常老的前端框架,由于几乎能够满足开发过程中的所有需求,所以至今依然有公司在使用它,这里就用一篇博客来带大家入个门;

1.1前后端分离

陈旧的开发模式
美工(ui工程师:出一个项目模型)
java工程师:将原有的html转成jsp,动态展示数据
缺点:
客户需要调节前端的展示效果
解决:由美工去重新排版,重新选色。
Vs
前后端分离
美工、java工程师都是独立工作的,彼此之间在开发过程中是没有任何交际。
在开发前约定数据交互的格式。
java工程师的工作:写方法返回数据如tree_data1.json
美工:只管展示tree_data1.json

1.2easyui的crud(dialog,datagrid、form讲解)

1、datagrid布局
2、dialog布局
3、form布局
4、通用的JsonBaseDao增删改方法
5、dao层
6、web层
7、功能完善

1.3 下载软件及相关jar包

1.esayui下载 http://www.jeasyui.com/download/v18.php
easyui增删改查_第1张图片

1.4引入jar包






若是显示效果不成功,打开浏览器F12开发 者模式调试仔细核对引入的路径
效果easyui增删改查_第2张图片

二.案例:

如图
easyui增删改查_第3张图片
easyui增删改查_第4张图片

MenuDao

package com.wxm.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wxm.entity.TreeNode;
import com.wxm.util.JsonBaseDao;
import com.wxm.util.JsonUtils;
import com.wxm.util.PageBean;
import com.wxm.util.StringUtils;

/**
 * 1、查询数据库所有数据用于easyui的tree树形展示(但是直接得来的数据格式easyui不识别)
 * 2、递归查询节点集合,形成子父节点关系,具备层次结构
 * 3、转格式
 * @author Administrator
 *
 */
public class MenuDao extends JsonBaseDao {
	/**
	 * List加上ObjectMapper可以转换成easyui的tree控件识别的json串
	 * @param map
	 * @param pageBean
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List listTreeNode(Map map, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		List> listMenu = this.listMenuAuth(map, pageBean);
		List listTreeNode = new ArrayList();
		this.listMapToListTreeNode(listMenu, listTreeNode);
		return listTreeNode;
	}
	
	/**
	 * 权限登录按照不同用户登录能够访问不同菜单
	 * @param map
	 * @param pageBean
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public List> listMenuAuth(Map map, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql = "select * from t_easyui_menu where true ";
		String id = JsonUtils.getParamVal(map, "Menuid");
		if(StringUtils.isNotBlank(id)) {
//			当前节点的ID当作子节点父ID进行查询
			sql += " and menuid in ("+id+") ";
		}else {
			sql += " and menuid=000";//超级管理员
		}
		return super.executeQuery(sql, pageBean);
	}
	
	/**
	 * List>
	 * ->【{Menuid:001,Menuname:学生管理,children:[]},{Menuid:001,Menuname:学生管理}】
	 * 	接下来需要递归查询子节点的集合存入当前节点
	 * 	
	 * @param map
	 * @param pageBean
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public List> listMenu(Map map, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql = "select * from t_easyui_menu where true ";
		String id = JsonUtils.getParamVal(map, "Menuid");
		if(StringUtils.isNotBlank(id)) {
//			当前节点的ID当作子节点父ID进行查询
			sql += " and parentid="+id;
		}else {
			sql += " and parentid=-1";
		}
		return super.executeQuery(sql, pageBean);
	}
	
	/**
	 * 需要将后台数据库查出来的数据格式转换成前台easyui所识别的数据
	 * @param map
	 * @param treeNode
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void mapToTreeNode(Map map, TreeNode treeNode) throws InstantiationException, IllegalAccessException, SQLException {
		treeNode.setId(map.get("Menuid").toString());
		treeNode.setText(map.get("Menuname").toString());
		treeNode.setAttributes(map);
		
//		treeNode.setChildren(children);
		Map childMap = new HashMap();
		childMap.put("Menuid", new String[] {treeNode.getId()});
//		查询出当前节点所拥有的子节点的集合
		List> listMenu = this.listMenu(childMap, null);
		List listTreeNode = new ArrayList();
		this.listMapToListTreeNode(listMenu, listTreeNode);
		treeNode.setChildren(listTreeNode);
	}
	
	public void listMapToListTreeNode(List> list, List listTreeNode) throws InstantiationException, IllegalAccessException, SQLException {
		TreeNode treeNode = null;
		for (Map map : list) {
			treeNode = new TreeNode();
			this.mapToTreeNode(map, treeNode);
			listTreeNode.add(treeNode);
		}
	}
}

UserDao

package com.wxm.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import java.util.UUID;

import com.wxm.util.JsonBaseDao;
import com.wxm.util.JsonUtils;
import com.wxm.util.PageBean;
import com.wxm.util.StringUtils;

public class UserDao extends JsonBaseDao {
	private String[] put;
	/**
	 * 用于查询用户分页列表所用
	 * 用于用户登录所用
	 * @param map
	 * @param pageBean
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List> list(Map map, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql = "select * from t_easyui_user_version2 where true ";
		String uid = JsonUtils.getParamVal(map, "uid");
		String upwd = JsonUtils.getParamVal(map, "upwd");
		if(StringUtils.isNotBlank(uid)) {
			sql += " and uid = "+uid;
		}
		if(StringUtils.isNotBlank(upwd)) {
			sql += " and upwd = "+upwd;
		}
		return super.executeQuery(sql, pageBean);
	}
	
	/**
	 * 通过用户登录的唯一账号,在用户父权限中间表中获取菜单ID的集合
	 * @param map
	 * @param pageBean
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public List> getMenusByUser(Map map, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql = "select * from t_easyui_usermenu where true ";
		String uid = JsonUtils.getParamVal(map, "uid");
		if(StringUtils.isNotBlank(uid)) {
			sql += " and uid = "+uid;
		}
		return super.executeQuery(sql, pageBean);
	}
	/**
	 * 修改
	 * @param map
	 * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 */
	public int edit(Map map) 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"}, map);
		
		
	}
	/**
	 * 新增
	 * @param map
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int add(Map map) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		
//    map.put("SerialNo", new String[] {UUID.randomUUID().toString()});
//		System.out.println( new String[] {UUID.randomUUID().toString()});//[Ljava.lang.String;@5c84099c
		
	map=(Map) new HashMap().put("SerialNo", new String[] {UUID.randomUUID().toString()});
		
		String sql="insert IGNORE  into t_easyui_user_version2 value(?,?,?,?) ";
		
		return super.executeUpdate(sql, new String[] {"SerialNo","uid","uname","upwd"}, map);
		
	}
	/**
	 * 删除
	 * @param map
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int del(Map map) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="delete t_easyui_user_version2 where serialno = ? ";
		return super.executeUpdate(sql, new String[] {"SerialNo"}, map);
		
	}
}


TreeNode

package com.wxm.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 针对easyui属性展示的json格式串进行了实体类的描述
 * @author Administrator
 *
 */
public class TreeNode {
	private String id;
	private String text;
	private List children = new ArrayList();
	private Map attributes = new HashMap();
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public List getChildren() {
		return children;
	}
	public void setChildren(List children) {
		this.children = children;
	}
	public Map getAttributes() {
		return attributes;
	}
	public void setAttributes(Map attributes) {
		this.attributes = attributes;
	}
	@Override
	public String toString() {
		return "TreeNode [id=" + id + ", text=" + text + ", children=" + children + ", attributes=" + attributes + "]";
	}
	
	
}

BaseDao

package com.wxm.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 
 */
public class BaseDao {
	// $.ajax
	protected interface Callback {
		public List foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException;
	}

	public List executeQuery(String sql, PageBean pageBean, Callback 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";
	}
}

package com.wxm.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("数据库连接(关闭)成功");
	}
}

package com.wxm.util;

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;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;





/**
 * 中文乱码处理
 * 
 */
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();
		}
	}


}

package com.wxm.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;

public class EntityBaseDao extends BaseDao {
	public List executeQuery(String sql, PageBean pageBean, Class clz) throws SQLException, InstantiationException, IllegalAccessException{
		return super.executeQuery(sql, pageBean, new Callback() {
			@Override
			public List 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 list = new ArrayList<>();
				while(rs.next()) {
					T t = (T) clz.newInstance();
					Field[] fields = clz.getDeclaredFields();
					for (Field field : fields) {
						field.setAccessible(true);
						field.set(t, rs.getObject(field.getName()));
					}
					list.add(t);
				}
				return list;
			}
		});
	}
	
	/**
	 * 通用的增删改方法
	 * @param sql	增删改的sql语句
	 * @param attrs	?所代表的实体类的属性
	 * @param t		实体类的实例
	 * @return
	 * @throws SQLException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public int executeUpdate(String sql, String[] attrs, T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Connection con = DBAccess.getConnection();
		PreparedStatement 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));
		}
		return pst.executeUpdate();
	}
}

package com.wxm.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> {
	public List> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		return super.executeQuery(sql, pageBean, new Callback>() {
			@Override
			public List> 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> list = new ArrayList<>();
//				获取源数据
				ResultSetMetaData md = rs.getMetaData();
				int count = md.getColumnCount();
				Map 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 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();
	}
}

package com.wxm.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 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 "";
	}
}

package com.wxm.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 *分页工具
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数


	//保留上一次 的请求地址
private String url="";
//保留上一次请求所携带的参数
private  Map paMap=new HashMap<>();
/**
 * pageBean初始化的方法
 * @param req
 */
    public void setRequest(HttpServletRequest req) {
    	//改变它第几页的数据
    	this.setPage(req.getParameter("page"));
    	//改变它每页展示的数据
//    	System.out.println(req.getParameter("rows"));
    	if(req.getParameter("rows")!=null) {
    	this.setRows(Integer.parseInt(req.getParameter("rows")));
    	}else {
    		this.setRows(10);
    	}
    	//控制页面是否分页
    	this.setPagination(req.getParameter("pagination"));
    	
    	
    	this.setUrl(req.getRequestURL().toString());//上一次的地址
    	this.setPaMap(req.getParameterMap());//上一次查询的参数
    }

	private void setPagination(String parameter) {
		// 当你填false就不分页
		if("false".equals(pagination)) {
			this.setPagination(false);
		}
	}
    public void setPage(String page) {
//    	如果不为空的时候
    	if(StringUtils.isNotBlank(page)) {
    		this.setPage(Integer.valueOf(page));
    	}
    }
	public String getUrl() {
	return url;
}

public void setUrl(String url) {
	this.url = url;
}



	public Map getPaMap() {
	return paMap;
}

public void setPaMap(Map paMap) {
	this.paMap = paMap;
}



	private boolean pagination = true;// 是否分页

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = 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;
	}

	/**
	 *获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}
/**
 * 最大页码
 * @return
 */
	public int getMaxPage() {
		return this.total%this.rows==0? this.total/this.rows:this.total/this.rows+1;
		
	}
	/**
	 * 获取下一页
	 * @return
	 */
  public int getNextPage() {
	return this.page1?this.page-1:this.page;
	  
  }
}


package com.wxm.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();
	}
}

package com.wxm.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);
	}

}

#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/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123




MenuAction

package com.wxm.web;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxm.dao.MenuDao;
import com.wxm.entity.TreeNode;
import com.zking.framework.ActionSupport;
import com.wxm.util.ResponseUtil;

public class MenuAction extends ActionSupport {
	private MenuDao menuDao = new MenuDao();

	public String menuTree(HttpServletRequest req,HttpServletResponse resp) {
		try {
			List listTreeNode = this.menuDao.listTreeNode(req.getParameterMap(), null);
			ObjectMapper om = new ObjectMapper();
			ResponseUtil.write(resp, om.writeValueAsString(listTreeNode));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

UserAction

package com.wxm.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.wxm.dao.UserDao;
import com.wxm.util.PageBean;
import com.wxm.util.ResponseUtil;
import com.zking.framework.ActionSupport;



public class UserAction extends ActionSupport{
	private UserDao userDao=new UserDao();
	public String login(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException {
		String code="index";//默认index首页
//		登录
		List> list=this.userDao.list(req.getParameterMap(), null);
		if(list!=null && list.size()==1) {
//			用户存在 
//			查询对应权限的菜单
			List> menulist=this.userDao.getMenusByUser(req.getParameterMap(), null) ;
			StringBuilder sb=new StringBuilder();
			for (Map map : menulist) {
				sb.append(","+map.get("menuId"));
			}
//			001,002
			req.setAttribute("menuIds", sb.substring(1));
		}else {
//			用户不存在
			req.setAttribute("msg", "用户不存在");
			code="login";
		}
		
//		code="login";//?
		return code;
	}

	/**
	 * easyui的datagrid的数据来源
	 * @param req
	 * @param resp
	 * @return
	 */
	public String list(HttpServletRequest req, HttpServletResponse resp) {
		Map map = new HashMap();
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			List> list = this.userDao.list(req.getParameterMap(), pageBean);
			map.put("total", pageBean.getTotal());
			map.put("rows", list);
			ObjectMapper om = new ObjectMapper();
			ResponseUtil.write(resp, om.writeValueAsString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.userDao.edit(req.getParameterMap());
			ObjectMapper om = new ObjectMapper();
			Map map = new HashMap();
			map.put("code", 1);
			map.put("msg", "成功");
			ResponseUtil.write(resp, om.writeValueAsString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.userDao.add(req.getParameterMap());
			
			ObjectMapper om = new ObjectMapper();
			Map map = new HashMap();
			map.put("code", 1);
			map.put("msg", "成功");
			ResponseUtil.write(resp, om.writeValueAsString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.userDao.del(req.getParameterMap());
			
			ObjectMapper om = new ObjectMapper();
			Map map = new HashMap();
			map.put("code", 1);
			map.put("msg", "成功");
			ResponseUtil.write(resp, om.writeValueAsString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}



	
	
	
	
	
		
		
	

userManage.js

$(function(){
	$('#dg').datagrid({    
	    url:'../userAction.action?methodName=list', 
	    pagination:true,
	    fitColumns:true,
	    columns:[[    
	        {field:'uid',title:'代码',width:100},    
	        {field:'uname',title:'名称',width:100},    
	        {field:'upwd',title:'价格',width:100,align:'right'}    
	    ]],
	    toolbar: [{
			iconCls: 'icon-add',
			handler: function(){
				$('#dd').dialog('open');  //编辑窗体的默认打开
				}
		},{
			iconCls: 'icon-edit',
			handler: function(){
				$('#dd').dialog('open');  //编辑窗体的默认打开
//				通过easyui的form空间直接回填选中行的数据
				var row=$('#dg').datagrid('getSelected');
				if(row){
					$("#ff").form('load',row);
				}else{
					alert("请选择你要修改的数据");
				}
			}
		},'-',{
			iconCls: 'icon-remove',
			handler: function(){alert('删除按钮')}
		}]

	}); 
})

function ok(){
	var SerialNo=$("#SerialNo").val();
	console.log("SerialNo----"+SerialNo);
	var url="../userAction.action?methodName=add";
	if(SerialNo !=null && SerialNo !=""){
		url="../userAction.action?methodName=edit";
	}
		$('#ff').form('submit', {    
		    url:url,   
		    
		    success:function(data){    
		    	var res=eval('('+data+')');
		    	console.log("url----"+url);
//		        比如说如果返回1代表成功,0代表失败,还有业务逻辑需要处理的话,由前端完成
		    	alert("----"+res.code);
		        if(res.code ==1){
		        	$("#dd").dialog('close');
		        	$("#dg").datagrid('reload');
		        }else{
		        	alert("失败");
		        }
		    }    
		});  
}

index.js

$(function(){
	$('#tt').tree({    
	    url:'menuAction.action?methodName=menuTree&&Menuid='+$("#menuIds").val(),
	    onClick: function(node){
			//alert(node.attributes.menuURL);  // 在用户点击的时候提示
	    	var content = '';
	    	if($("#menuTab").tabs('exists',node.text)){
	    		$("#menuTab").tabs('select',node.text)
	    	}else{
	    		$('#menuTab').tabs('add',{    
				    title:node.text,    
				    content:content,    
				    closable:true  
				}); 
	    	}
		}
	}); 
})

index.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>









	
后台管理主界面



	
	
north region
左侧的菜单栏加载区域
    east region
    south region
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    
    
    
    
    用户登录界面
    
    
    
    uid:
    upwd:
    ${msg }

    在这里插入图片描述

    注意引用js

    userManage.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    
    
    
    
    
    
    
    
    	
    人员信息维护界面
    
    
    

    datagrid_data1.json

    {"total":28,"rows":[
    	{"uid":"FI-SW-01","uname":"Koi","upwd":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},
    	{"uid":"K9-DL-01","uname":"Dalmation","upwd":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},
    	{"uid":"RP-SN-01","uname":"Rattlesnake","upwd":12.00,"status":"P","listprice":38.50,"attr1":"Venomless","itemid":"EST-11"},
    	{"uid":"RP-SN-01","uname":"Rattlesnake","upwd":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"},
    	{"uid":"RP-LI-02","uname":"Iguana","upwd":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"},
    	{"uid":"FL-DSH-01","uname":"Manx","upwd":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"},
    	{"uid":"FL-DSH-01","uname":"Manx","upwd":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"},
    	{"uid":"FL-DLH-02","uname":"Persian","upwd":12.00,"status":"P","listprice":23.50,"attr1":"Adult Female","itemid":"EST-16"},
    	{"uid":"FL-DLH-02","uname":"Persian","upwd":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"},
    	{"uid":"AV-CB-01","uname":"Amazon Parrot","upwd":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}
    ]}
    
    

    访问地址 http://localhost:8080/pro_easyu/login.jsp
    easyui增删改查_第5张图片
    增加
    easyui增删改查_第6张图片
    修改easyui增删改查_第7张图片
    修改后
    easyui增删改查_第8张图片

    你可能感兴趣的:(后端,前端)