使用easyUI实现后台管理(CRUD)的全过程

前言:避免遗忘,附上所有代码;没有分页功能,待续

1、效果图

使用easyUI实现后台管理(CRUD)的全过程_第1张图片

2、该JaveWeb项目的目录结构

util包下都是对jdbc的一些封装,与本篇博文主旨关系不大,感兴趣可移步:

https://blog.csdn.net/Carl_changxin/article/details/82112563

使用easyUI实现后台管理(CRUD)的全过程_第2张图片

3、userList.html的代码:

页面中的css和js下载地址:http://www.jeasyui.net/download/

页面中的难点解释:

(1)url="getUserList"  method="post" :    这里表示向后台发出servlet请求,要求返回json数据





	Insert title here
	
	
	
	
	


		
       
First Name Last Name Phone Email
User Information

页面的js代码

SaveUser方法的解释:

(1)点击New User选择某条记录后点击Edit User 都会弹出对话框id=dlg

(2)对话框中有Save按钮,在点击Save之前要判断当前是新增还是更新,再做相应的后台处理

4、servlet包下的所有类

注意:我都是用注解的方式配置本应在web.xml中配置的servlet-mapping

GetUserListServlet.java:

package servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import entity.User;

@WebServlet(name = "getUserListServlet", urlPatterns = { "/getUserList" })
public class GetUserListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
        //在这个findUser方法中rows是key(必须是rows,才能被easyui识别),查出来的user数据是一个list作为值
		Map map = user.findUser();
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(JSONObject.toJSON(map));
	
	}

}

SaveUserServlet.java:

package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import entity.User;
import util.GetParams;

/**
 * Servlet implementation class AddBlogServlet
 */
@WebServlet(name = "saveUserServlet", urlPatterns = { "/saveUser" })
public class SaveUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得参数,构造对象,接收参数,保存对象到数据库
		Map params = request.getParameterMap();
				
		@SuppressWarnings("unchecked")
		User user = (User) GetParams.getInstance().formatBean(params, User.class);
		int res = user.save();
		Map map = new HashMap();
		//save方法的返回值是int,成功则设置个标志code=200
		if(res == 1) {
			map.put("code", 200);
		}else{
			map.put("code", 500);
		}
		response.getWriter().print(JSONObject.toJSON(map));
	}
}

UpdateUserServlet.java:

package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import entity.User;
import util.GetParams;

/**
 * Servlet implementation class UpdateBlogServlet
 */
@WebServlet(name = "updateUserServlet", urlPatterns = { "/updateUser" })
public class UpdateUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得参数,构造对象,接收参数,保存对象到数据库
		Map params = request.getParameterMap();
		User user = (User) GetParams.getInstance().formatBean(params, User.class);
		int res = user.alertById();
		Map map = new HashMap();
		if(res == 1) {
			map.put("code", 200);
		}else{
			map.put("code", 500);
		}
		response.getWriter().print(JSONObject.toJSON(map));
	}

	
}

DeleteUserServlet.java:

package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import entity.User;

@WebServlet(name = "deleteUserServlet", urlPatterns = { "/deleteUser" })
public class DeleteUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		User user = new User();
		user.setId(Integer.valueOf(id));
		int res = user.remove();
		Map map = new HashMap();
		if(res == 1) {
			map.put("code", 200);
		}else{
			map.put("code", 500);
		}
		response.getWriter().print(JSONObject.toJSON(map));
	}

}

5、entity包

User.java

package entity;

import util.BaseDao;

public class User extends BaseDao{
	
	public User() {
		super("t_user");
	}
	private Integer id;
	private String firstname;
	private String lastname;
	private String phone;
	private String email;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	
}

数据库:

使用easyUI实现后台管理(CRUD)的全过程_第3张图片

6、util包

BaseDao.java

package util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *1、实体类去继承该类,该类会提供增删改查的方法,让实体对象去调用
 *2、 实体类对应数据库中的一张表,一个实体对象对应表中的一条数据
 *3、该类中提供的增删改查方法,只是拼接了sql语句,再交给JDBC去做
 *4、sql语句的可变部分可以看做是对象的属性和属性值,因此可以通过反射去获取实体对象的属性和属性值,拼接sql语句
 * @param 
 */
public class BaseDao {
	private JDBC jdbc = JDBC.getInstance();
	
	@SuppressWarnings("rawtypes")
	private Class cls = this.getClass();
	private String tableName;
	
	public BaseDao(String tableName){
		this.tableName = tableName;
	}
	/**
	 * 保存对象到数据库
	 * insert into 表名(列名/属性名...) value (属性值);
	 * @return 影响的行数
	 */
	public int save(){
		/**拼接插入语句*/
		StringBuffer insertSql = new StringBuffer("insert into "+tableName+" (");
		StringBuffer fieldsSql = new StringBuffer();
		StringBuffer fieldsValSql = new StringBuffer();
		Field[] fields = cls.getDeclaredFields();
		try {
			for(Field f : fields){
				f.setAccessible(true);
				//当属性名不是id并且属性值不为空时,把该属性当作插入条件之一
				if(!"id".equals(f.getName()) && f.get(this) != null ){
						fieldsSql.append("`"+f.getName()+"`"+",");
						fieldsValSql.append("'"+f.get(this)+"'"+",");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(fieldsSql.length()!=0) {
			fieldsSql.replace(fieldsSql.length()-1, fieldsSql.length(), "");
			fieldsValSql.replace(fieldsValSql.length()-1, fieldsValSql.length(), "");
		}
		insertSql.append(fieldsSql+") value ("+fieldsValSql+");");
		System.out.println(insertSql);
		return jdbc.insert(insertSql.toString());
		
	}
	
	/**
	 * 根据当前对象的属性进行删除,以不为空的属性作为删除的过滤添加
	 * delete from tableName where 属性1名=属性1值 and 属性2名=属性2值 ...
	 * @return 影响的行数
	 */
	public int remove(){
		StringBuffer deleteSql = new StringBuffer();
		StringBuffer attrVal = new StringBuffer();
		/**获得类中所有的属性*/
		Field[] fields = cls.getDeclaredFields();
		for(Field f : fields){
			f.setAccessible(true);
			try {
				if(f.get(this) != null){
					attrVal.append("`"+f.getName()+"`='"+f.get(this)+"' and ");
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		attrVal.replace(attrVal.length()-4, attrVal.length(), "");
		deleteSql.append("delete from `"+tableName+"` where "+attrVal+";");
		System.out.println(deleteSql);
		return jdbc.delete(deleteSql.toString());
	}
	
	/**
	 * 修改对象对应数据库中的列
	 * //update t_user set name='',age='' where id=''
	 * @return 影响的行数
	 */
	public int alertById(){
		StringBuffer updateSql = new StringBuffer();
		StringBuffer attrVal = new StringBuffer();
		Integer idVal = null;
		/**获得类中所有的属性*/
		Field[] fields = cls.getDeclaredFields();
		for(Field f : fields){
			f.setAccessible(true);
			try {
				if(!"id".equals(f.getName())){
					if(f.get(this) != null){
						attrVal.append("`"+f.getName()+"`='"+f.get(this)+"',");
					}
					
				}else{
					if(f.get(this) == null){
						System.out.println("id没有值");
					}else{
						idVal = (Integer) f.get(this);
					}
				}
				
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		attrVal.replace(attrVal.length()-1, attrVal.length(), "");
		updateSql.append("update `"+tableName+"` set "+attrVal+" where "+"`id`='"+idVal+"';");
		System.out.println(updateSql);
		return jdbc.update(updateSql.toString());
	}
	
	/**
	 * 查找符合条件的数据
	 * select * from tableName where ...
	 * @return 查找到的结果,转化成对象
	 */
	public List find(){
		
		StringBuffer querySql = new StringBuffer("select * from "+tableName);
		StringBuffer attrVal = new StringBuffer();
		Field[] fields = cls.getDeclaredFields();
		for(Field f : fields){
			f.setAccessible(true);
			try {
				if(f.get(this) !=null){
					attrVal.append("`"+f.getName()+"`='"+f.get(this)+"' and ");
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		if(attrVal.length() != 0){
			attrVal.replace(attrVal.length()-4, attrVal.length(), "");
			querySql.append(" where "+attrVal+";");
		}else{
			querySql.append(";");
		}
		System.out.println(querySql);
		
		//查询出来的结果开始是结果集,然后转化成List>集合,再转化成对象
		List> lists = jdbc.query(querySql.toString());
//		System.out.println(lists.size());
		//遍历lists集合
		try {
			List list = new ArrayList();//用来存放对象
			for(Map m : lists){
				
				@SuppressWarnings("unchecked")
				T t = (T)cls.newInstance();
				//遍历Map集合,一个Map集合对应一个对象
				for( Map.Entry entry: m.entrySet() ){
					//根据列名称,获取当前对象的对应该列的属性
					Field f = cls.getDeclaredField(entry.getKey());
					//设置对象的属性值
					f.setAccessible(true);
					f.set(t, entry.getValue());
				}
				list.add(t);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 封装分页
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map find(Integer page,Integer rows){
		//一个map集合用来存放查询出来的一条数据,按照<列名,列值>保存
		Map map = new HashMap();
		//T设置成Map就可以存放多条查询出来的数据
		List list = new ArrayList();
		//获得对象所有的属性(包括私有属性)
		Field[] fields = cls.getDeclaredFields();
		StringBuffer selectSqlBuf = new StringBuffer("select * from "+tableName+" where 1=1");
		try {
			for(Field f : fields) {
				String proName = f.getName();//age
				f.setAccessible(true);
				Object value = f.get(this);//获得当前属性的值
					if(value!=null) {
						selectSqlBuf.append(" and "+proName+"='"+value+"'");
					}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		selectSqlBuf.append(" limit "+(page-1)*rows+","+rows+";");
		System.out.println(selectSqlBuf);
		List> mapList = jdbc.query(selectSqlBuf.toString());
		try {
			for(Map m :mapList) {
				//一个对象对应数据库中的一条数据,m对应当前的一条数据,即也对应一个对象
				//通过反射实例化一个对象,去封装循环出来的每一条数据
				T t = (T) cls.newInstance();
				for (Map.Entry entry : m.entrySet()) {
				   String key = entry.getKey().toString();
				   Object value = entry.getValue();
				   Field f = cls.getDeclaredField(key);//根据属性名称,获取当前对象的属性
				   f.setAccessible(true);
				   f.set(t, value);
				 }
				list.add(t);
			}
		} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
				| IllegalArgumentException e) {
			e.printStackTrace();
		}
		//计算总共有多少页
		Long total = Long.valueOf(jdbc.query("select count(1) as total  from "+tableName).get(0).get("total")+"");
		Long pages = (total+rows-1)/rows;
		map.put("data", list);
		map.put("page",page);
		map.put("rows",rows);
		map.put("pages", pages);
		//map中保存了当前页面要显示的数据list,页码page,条数rows,总页数pages
		return map;
	}
	
	public Map findUser(){
		//一个map集合用来存放查询出来的一条数据,按照<列名,列值>保存
		Map map = new HashMap();
		//T设置成Map就可以存放多条查询出来的数据
		List list = new ArrayList();
		//获得对象所有的属性(包括私有属性)
		Field[] fields = cls.getDeclaredFields();
		StringBuffer selectSqlBuf = new StringBuffer("select * from "+tableName+" where 1=1");
		try {
			for(Field f : fields) {
				String proName = f.getName();//age
				f.setAccessible(true);
				Object value = f.get(this);//获得当前属性的值
					if(value!=null) {
						selectSqlBuf.append(" and "+proName+"='"+value+"'");
					}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		System.out.println(selectSqlBuf);
		List> mapList = jdbc.query(selectSqlBuf.toString());
		try {
			for(Map m :mapList) {
				//一个对象对应数据库中的一条数据,m对应当前的一条数据,即也对应一个对象
				//通过反射实例化一个对象,去封装循环出来的每一条数据
				T t = (T) cls.newInstance();
				for (Map.Entry entry : m.entrySet()) {
				   String key = entry.getKey().toString();
				   Object value = entry.getValue();
				   Field f = cls.getDeclaredField(key);//根据属性名称,获取当前对象的属性
				   f.setAccessible(true);
				   f.set(t, value);
				 }
				list.add(t);
			}
		} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
				| IllegalArgumentException e) {
			e.printStackTrace();
		}
		map.put("rows", list);
		return map;
	}
}

JDBC.java

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
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;
import java.util.Properties;

/**
 * 1、和数据库建立连接
 * 2、处理DB_Dao传送过来的sql语句,包括增删改查
 */
public class JDBC {
	//饿汉模式
	private static JDBC jdbc = new JDBC();
	private String driver;
	private String url;
	private String name;
	private String password;
	private Connection conn;
	
	public static void main(String[] args) {
		JDBC jdbc = new JDBC();
	}
	/**
	 * 单例模式,私有化构造方法
	 */
	private JDBC(){
		readProperties();
	}
	
	//获得JDBC对象的公开方法
	public static JDBC getInstance(){
		return jdbc;
	}
	
	//读取配置文件
	private void readProperties(){
		try {
			Properties p = new Properties();
			InputStream is = JDBC.class.getResourceAsStream("mysql.properties");
			p.load(is);
			is.close();
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			name = p.getProperty("name");
			password = p.getProperty("password");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//连接数据库
	private Connection conn(){
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url,name,password);
			
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 增删改操作
	 * @return 返回受影响的行数
	 */
	private int DML(String sql,Object...paras){
		PreparedStatement ps = null;
		try {
			conn = conn();
			ps = conn.prepareStatement(sql);
			/**
			 * 设置参数
			 */
			int i=1;
			for(Object o : paras){
				ps.setObject(i++, o);
			}
			
			return ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(ps != null){
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return 0;
	}
	
	
	public int insert(String sql,Object...paras){
		
		return DML(sql,paras);
	}
	
	public int update(String sql,Object...paras){
		
		return DML(sql,paras);
	}
	
	public int delete(String sql,Object...paras){
		
		return DML(sql,paras);
	}
	
	private List> DQL(String sql,Object...paras){
		List> lists = new ArrayList>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = conn();
			ps = conn.prepareStatement(sql);
			
			int i = 1;
			for(Object o : paras){
				ps.setObject(i++, o);
			}
			rs = ps.executeQuery();
			//对结果集进行操作
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while(rs.next()){
				Map map = new HashMap();
				for(int j=1;j<=columnCount;j++){
					map.put(rsmd.getColumnName(j), rs.getObject(j));
				}
				lists.add(map);
			}
			return lists;
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps != null){
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	public List> query(String sql,Object...paras){
		return DQL(sql,paras);
	}
	
	
}

GetParams.java:

package util;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;


public class GetParams {
	
	private static GetParams param = new GetParams();
	/**
	 * 私有化构造方法,实现单例模式
	 */
	private GetParams(){
		
	};
	
	public static GetParams getInstance() {
		
		return param;
	}
	
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public  T formatBean(Map params,Class  cls){
		try {
			//通过反射将传过来的值,赋值给对象的属性
			Iterator iterator = params.keySet().iterator();
			T t = (T) cls.newInstance();
			while(iterator.hasNext()){
				String key = iterator.next().toString();
				Field field;
				try {
					field = cls.getDeclaredField(key);
					String[] values = params.get(key);//取得当前参数的值
					if(values!=null&&values.length!=0){
						field.setAccessible(true);
						String type = field.getType().getName();//取得当前的key所对应属性的类型
						if("java.lang.String".equals(type)){
							field.set(t, values[0]);
						}else if("java.lang.Integer".equals(type)){
							field.set(t, Integer.valueOf(values[0]));
						}
					}
				} catch (Exception e) {
					System.out.println(key+"这个属性在对象里没有");
				}
			}
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
}

mysql.properties:

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/easyui
name=root
password=1

 

你可能感兴趣的:(使用easyUI实现后台管理(CRUD)的全过程)