util包下都是对jdbc的一些封装,与本篇博文主旨关系不大,感兴趣可移步:
https://blog.csdn.net/Carl_changxin/article/details/82112563
页面中的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
SaveUser方法的解释:
(1)点击New User 或 选择某条记录后点击Edit User 都会弹出对话框id=dlg
(2)对话框中有Save按钮,在点击Save之前要判断当前是新增还是更新,再做相应的后台处理
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));
}
}
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));
}
}
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));
}
}
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));
}
}
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;
}
}
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
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);
}
}
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;
}
}
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/easyui
name=root
password=1