mobile.dao包
BaseDao.java
package mobile.dao;
import java.lang.reflect.Field;
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.List;
import mobile.util.JdbcUtil;
public abstract class BaseDao<T> {
public List<T> getList(Class<T> clazz, String sql, Object... params) {
List<T> list = new ArrayList<>();
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
// 缁欏崰浣嶇锛熻祴鍊�
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
rs = stmt.executeQuery();
// 浠庣粨鏋滈泦涓幏鍙栨墍鏈夌殑瀛楁
ResultSetMetaData md = rs.getMetaData();
while (rs.next()) {
// 鐢ㄥ弽灏勫垱寤轰竴涓璞�
T obj = clazz.newInstance();
// 閬嶅巻鎵�湁鐨勫瓧娈�
for (int i = 1; i <= md.getColumnCount(); i++) {
// 鑾峰彇褰撳墠鍒楃殑鍒楀悕锛屽鏋滃垪鏈夊埆鍚嶏紝灏辫繑鍥炲埆鍚�
String columnName = md.getColumnLabel(i).toLowerCase();
// 鑾峰彇瀛楁鐨勫�
Object columnValue = rs.getObject(columnName);
if (columnValue == null) {
// 缁撴潫鏈寰幆
continue;
}
// 鑾峰彇瀛楁鍊肩殑绠�煭绫诲瀷,渚嬪String,Integer
String type = columnValue.getClass().getSimpleName();
// oracle浼氬皢number绫诲瀷鐨勫瓧娈佃В鏋愭垚BigDecimal绫诲瀷,mysql浼氬皢int鍜宨nteger绫诲瀷瑙f瀽鎴恑nt鎴朓nteger绫诲瀷
switch (type) {
case "BigDecimal":
// 濡傛灉鍊奸噷闈㈡湁"."锛岃褰撴垚灏忔暟鏉ヨ幏鍙�
if (columnValue.toString().contains(".")) {
columnValue = rs.getDouble(columnName);
} else {
columnValue = rs.getInt(columnName);
}
break;
case "int":
case "Integer":
columnValue = rs.getInt(columnName);
break;
}
// System.out.println("鍒楀悕锛� + columnName + "锛屽瓧娈靛�锛� +
// columnValue + "锛岀被鍨嬶細" + type);
// 灏嗚幏鍙栧埌鐨勫瓧娈电殑鍊煎皝瑁呭埌璇ュ瓧娈靛搴旂殑鍚屽悕灞炴�涓�
// 鑾峰彇绉佹湁灞炴�锛屾牴鎹睘鎬у悕鑾峰彇
Field field = clazz.getDeclaredField(columnName);
// 鍘婚櫎绉佹湁灞炴�璁块棶闄愬埗
field.setAccessible(true);
// 灏嗗瓧娈靛�璧嬬粰瀵硅薄鐨勫悓鍚嶅睘鎬�
field.set(obj, columnValue);
}
// System.out.println("*****************************************");
// 灏嗗璞℃坊鍔犲埌闆嗗悎涓�
list.add(obj);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mobile.util.JdbcUtil.closeAll(rs, stmt, conn);
}
return list;
}
public T getBean(Class<T> clazz, String sql, Object... params) {
// 鍒涘缓瑕佽繑鍥炵殑瀵硅薄
T obj = null;
Connection conn = mobile.util.JdbcUtil.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
// 缁欏崰浣嶇锛熻祴鍊�
for (int i =0 ; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
rs = stmt.executeQuery();
// 浠庣粨鏋滈泦涓幏鍙栨墍鏈夌殑瀛楁
ResultSetMetaData md = rs.getMetaData();
if (rs.next()) {
// 鐢ㄥ弽灏勫垱寤哄璞�
obj = clazz.newInstance();
// 閬嶅巻鎵�湁鐨勫瓧娈�
for (int i = 1; i <= md.getColumnCount(); i++) {
// 鑾峰彇褰撳墠鍒楃殑鍒楀悕锛屽鏋滃垪鏈夊埆鍚嶏紝灏辫繑鍥炲埆鍚�
String columnName = md.getColumnLabel(i).toLowerCase();
// 鑾峰彇瀛楁鐨勫�
Object columnValue = rs.getObject(columnName);
if (columnValue == null) {
// 缁撴潫鏈寰幆
continue;
}
// 鑾峰彇瀛楁鍊肩殑绠�煭绫诲瀷,渚嬪String,Integer
String type = columnValue.getClass().getSimpleName();
// oracle浼氬皢number绫诲瀷鐨勫瓧娈佃В鏋愭垚BigDecimal绫诲瀷,mysql浼氬皢int鍜宨nteger绫诲瀷瑙f瀽鎴恑nt鎴朓nteger绫诲瀷
switch (type) {
case "BigDecimal":
// 濡傛灉鍊奸噷闈㈡湁"."锛岃褰撴垚灏忔暟鏉ヨ幏鍙�
if (columnValue.toString().contains(".")) {
columnValue = rs.getDouble(columnName);
} else {
columnValue = rs.getInt(columnName);
}
break;
case "int":
case "Integer":
columnValue = rs.getInt(columnName);
break;
}
// System.out.println("鍒楀悕锛� + columnName + "锛屽瓧娈靛�锛� +
// columnValue + "锛岀被鍨嬶細" + type);
// 灏嗚幏鍙栧埌鐨勫瓧娈电殑鍊煎皝瑁呭埌璇ュ瓧娈靛搴旂殑鍚屽悕灞炴�涓�
// 鑾峰彇绉佹湁灞炴�锛屾牴鎹睘鎬у悕鑾峰彇
Field field = clazz.getDeclaredField(columnName);
// 鍘婚櫎绉佹湁灞炴�璁块棶闄愬埗
field.setAccessible(true);
// 灏嗗瓧娈靛�璧嬬粰瀵硅薄鐨勫悓鍚嶅睘鎬�
field.set(obj, columnValue);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mobile.util.JdbcUtil.closeAll(rs, stmt, conn);
}
return obj;
}
}
MobileDao.java
package mobile.dao;
import java.util.List;
import mobile.entity.Mobile;
public interface MobileDao {
int insert(Mobile stu);
int update(Mobile stu);
int delete(Integer id);
List<Mobile>queryAll();
Mobile queryById(Integer id);
}
mobileDaoImpl包
MobileDaoImpl.java
package mobile.daoImpl;
import java.util.List;
import mobile.dao.BaseDao;
import mobile.dao.MobileDao;
import mobile.entity.Mobile;
import mobile.util.JdbcUtil;
public class MobileDaoImpl extends BaseDao<Mobile> implements MobileDao{
//鎻掑叆鏂规硶閲嶅啓
public int insert(Mobile mob) {
String sql="insert into mobile(brand,model,price,totalnum) values(?,?,?,?)";
int i=JdbcUtil.executeUpdate(sql, mob.getBrand(),mob.getModel(),mob.getPrice(),mob.getTotalnum());
return i;
}
//淇敼鎵嬫満淇℃伅
public int update(Mobile mob) {
String sql="update mobile set brand=?,model=?,price=?,totalnum=? where id=?";
int i=JdbcUtil.executeUpdate(sql, mob.getBrand(),mob.getModel(),mob.getPrice(),mob.getTotalnum(),mob.getId());
return i;
}
//鍒犻櫎鎵嬫満淇℃伅
public int delete(Integer id) {
String sql="delete from mobile where id=?";
int i=JdbcUtil.executeUpdate(sql, id);
return i;
}
//鏌ヨ鍏ㄩ儴鎵嬫満淇℃伅
public List<Mobile> queryAll() {
String sql="select * from mobile";
List<Mobile>list=this.getList(Mobile.class, sql);
return list;
}
//鏍规嵁ID鏌ヨ鎵嬫満淇℃伅
public Mobile queryById(Integer id) {
String sql="select * from mobile where id=?";
Mobile mob=this.getBean(Mobile.class, sql, id);
return mob;
}
}
mobile.entity包
Mobile.java
package mobile.entity;
public class Mobile {
private Integer id;
private String brand;
private String model;
private Double price;
private Integer totalnum;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getTotalnum() {
return totalnum;
}
public void setTotalnum(Integer totalnum) {
this.totalnum = totalnum;
}
public Mobile(Integer id, String brand, String model, Double price, Integer totalnum) {
super();
this.id = id;
this.brand = brand;
this.model = model;
this.price = price;
this.totalnum = totalnum;
}
public Mobile() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Mobile [id=" + id + ", name=" + brand + ", model=" + model + ", price=" + price + ", totalnum="
+ totalnum + "]";
}
}
mobile.util
package mobile.util;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* jdbc鎿嶄綔鏁版嵁搴撶殑宸ュ叿绫�灏佽閫氱敤鐨勪唬鐮�
*
* @author lujun
*
*/
public class JdbcUtil {
// 鏁版嵁搴撻┍鍔ㄧ被
private static String driver;
// 鏁版嵁搴撴湇鍔″櫒鐨勫湴鍧�
private static String url;
// 杩炴帴鏈嶅姟鍣ㄧ殑鐢ㄦ埛鍚�
private static String user;
// 杩炴帴鏈嶅姟鍣ㄧ殑鐢ㄦ埛瀵嗙爜
private static String password;
// 鍔犺浇椹卞姩鍙渶瑕佸姞杞戒竴娆★紝鍙互鏀惧埌闈欐�浠g爜鍧椾腑
static {
try {
// 瀵筪b.properties鏂囦欢鐨勮鍙�
Properties prop = new Properties();
// 鍔犺浇鏂囦欢锛屽苟杞崲涓鸿緭鍏ユ祦锛屼粠娴佷腑璇诲彇鏁版嵁
InputStream stream = JdbcUtil.class.getResourceAsStream("/db.properties");
prop.load(stream);
// 璋冪敤getProperty(String key)锛屾牴鎹甼ey鑾峰彇鐩稿簲鐨剉alue
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driver = prop.getProperty("driver");
// 鍔犺浇椹卞姩
Class.forName(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 鑾峰彇涓�釜杩炴帴
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
// 鍏抽棴璧勬簮
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 閫氱敤澧炲垹鏀规柟娉�鍙傛暟1锛氳鎵ц鐨凞ML璇彞(insert,update,delete璇彞)
* 鍙傛暟2锛氱粰DML璇彞涓殑锛熻祴鐨勪竴缁勫�,鎶婂崰浣嶇鍊肩粺涓�斁鍒板彲鍙樺弬鏁颁腑锛屽彲鍙樺弬鏁板彲浠ュ綋鎴愭暟缁勭敤
* 杩斿洖鍊硷細鎵ц澧炲垹鏀瑰奖鍝嶆暟鎹簱鐨勮鏁帮紝濡傛灉鎴愬姛锛岃繑鍥�锛屽け璐ヨ繑鍥�
*/
public static int executeUpdate(String sql, Object... params) {
int count = 0;
// 鍒涘缓杩炴帴
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = null;
try {
// 鍒涘缓棰勭紪璇戠殑statement
stmt = conn.prepareStatement(sql);
// 缁欏崰浣嶇?璧嬪�
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
count = stmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 鍏抽棴璧勬簮
JdbcUtil.closeAll(null, stmt, conn);
}
return count;
}
}
db.properties
#key=value driver=com.mysql.jdbc.Driver url = jdbc:mysql://127.0.0.1:3306/mysqldb user=root password=tiger
WebRoot
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="list.jsp">显示所有手机信息</a>
</body>
</html>
list.jsp
<%@page import="mobile.daoImpl.MobileDaoImpl"%>
<%@page import="mobile.entity.Mobile"%>
<%@page import="mobile.dao.MobileDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>手机列表</h2>
<table width="50%" border="1" cellspacing="0" cellpadding="10">
<tr>
<td>手机编号</td>
<td>品牌</td>
<td>型号</td>
<td>价格</td>
<td>总数</td>
</tr>
<%
MobileDao dao=new MobileDaoImpl();
List<Mobile>list=dao.queryAll();
for(Mobile mob:list){
%>
<tr>
<td><%=mob.getId()%></td>
<td><%=mob.getBrand()%></td>
<td><%=mob.getModel()%></td>
<td><%=mob.getPrice()%></td>
<td><%=mob.getTotalnum() %></td>
<td>
<!-- 如果点超链接时,需要响应js事件,那么建议把href写成
javascript:void(0)或者javascript:;表示让超链接不作任何跳转,只响应js事件 -->
<a href="javascript:void(0)" onclick="deleteById(<%=mob.getId()%>)" >删除</a></td>
</tr>
<%
}
%>
</table>
<a href="add.jsp">添加手机</a>
<script>
function deleteById(id){
// confirm()函数会弹出一带确认和取消按钮的对话框,如果点击确认按钮,函数返回true,否则返回false
var flag= confirm('是否确认删除此记录');
if(flag){
//alert(id);
//发送请求给doDelete.jsp页面, location.href是改变请求的路径,发送get请求
location.href="doDelete.jsp?id="+id;
}
}
</script>
<br>
</body>
</html>
add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>添加手机页面</h2>
<form action="doAdd.jsp" method="post">
品牌:<input type="text" name="brand"> <br>
型号:<input type="text" name="model"> <br>
价格:<input type="text" name="price"> <br>
总数:<input type="text" name="totalnum"> <br>
<input type="submit" value="添加新的手机">
<br>
</from>
</body>
</html>
doAdd.jsp
<%@page import="mobile.entity.Mobile"%>
<%@page import="mobile.daoImpl.MobileDaoImpl"%>
<%@page import="mobile.dao.MobileDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'doAdd.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//设置请求编码,防止中文乱码
request.setCharacterEncoding("UTF-8");
String brand=request.getParameter("brand");
String model=request.getParameter("model");
double price=Double.parseDouble(request.getParameter("price"));
int totalnum=Integer.parseInt(request.getParameter("totalnum"));
Mobile mob=new Mobile();
mob.setBrand(brand);;
mob.setModel(model);
mob.setPrice(price);
mob.setTotalnum(totalnum);
MobileDao dao=new MobileDaoImpl();
int i=dao.insert(mob);
if(i>0){
//跳转到list.jsp页面,刷新页面,response.sendRedirect:重新发请求到新页面
response.sendRedirect("list.jsp");
}
%>
<br>
</body>
</html>
doDelete.jsp
<%@page import="mobile.dao.MobileDao"%>
<%@page import="mobile.daoImpl.MobileDaoImpl"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'doDelete.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//获取要删除手机的编号
int id=Integer.parseInt(request.getParameter("id"));
//调用Dao的删除方法
MobileDao dao=new MobileDaoImpl();
int i=dao.delete(id);
if(i>0){
//跳转到list.jsp页面,刷新页面response.sendRedirect:重新发送请求到新的页面
response.sendRedirect("list.jsp");
}
%>
<br>
</body>
</html>