Java+MyEclipse+Tomcat (五)DAO和Java Bean实现数据库和界面分开操作
? ? ? ? 此篇文章主要講述通過DAO和Java Bean操作數(shù)據(jù)庫(kù),把鏈接數(shù)據(jù)庫(kù)、數(shù)據(jù)庫(kù)操作、前端界面顯示分模塊化實(shí)現(xiàn)。參考前文:
? ? ? ??Java+MyEclipse+Tomcat (一)配置過程及jsp網(wǎng)站開發(fā)入門
? ? ? ??Java+MyEclipse+Tomcat (二)配置Servlet及簡(jiǎn)單實(shí)現(xiàn)表單提交
? ? ? ??Java+MyEclipse+Tomcat (三)配置MySQL及查詢數(shù)據(jù)顯示在JSP網(wǎng)頁(yè)中
? ? ? ??Java+MyEclipse+Tomcat (四)Servlet提交表單和數(shù)據(jù)庫(kù)操作
? ? ? ?DAO和Java Bean是對(duì)JDBC進(jìn)行分層、模塊化的最有效兩個(gè)方法。DAO(數(shù)據(jù)庫(kù)操作對(duì)象,Database Access Object)是JDBC下常用模式,DAO出現(xiàn)之前,操作數(shù)據(jù)庫(kù)的代碼與業(yè)務(wù)代碼都出現(xiàn)在Servlet或者JSP中,不利用業(yè)務(wù)代碼的分離。DAO出現(xiàn)后,所有與數(shù)據(jù)庫(kù)相關(guān)的操作全被拿到了DAO層實(shí)現(xiàn),Servlet或JSP只操作Java Bean或者DAP層,而DAO層值操作數(shù)據(jù)庫(kù)。
? ? ? ? 下面直接上代碼,希望文章對(duì)你有所幫助~文章部分參考Java Web王者歸來(lái)。
? ? ? ? 下載地址:http://download.csdn.net/detail/eastmount/8714395
一. 項(xiàng)目結(jié)構(gòu)
? ? ? ?該項(xiàng)目的結(jié)構(gòu)如下圖所示:
? ? ? ? 其中bean中Student.java是對(duì)應(yīng)數(shù)據(jù)庫(kù)學(xué)生表,主要包括setId()、getId()等操作;DAO中StudentDAO.java是對(duì)學(xué)生表的數(shù)據(jù)庫(kù)增刪改查操作;util中JDBCConnect.java主要是連接數(shù)據(jù)庫(kù)MySQL的操作;student.jsp是顯示數(shù)據(jù)的JSP前端界面。同時(shí)需要lib文件夾中加載mysql-connector-java.jar包。
二. 創(chuàng)建數(shù)據(jù)庫(kù)
? ? ? ? 打開MySQL,輸入默認(rèn)超級(jí)root用戶的密碼,然后數(shù)據(jù)庫(kù)的操作如下代碼:
--創(chuàng)建數(shù)據(jù)庫(kù) create database TestDao; --使用數(shù)據(jù)庫(kù) use TestDao; --創(chuàng)建學(xué)生表 create table student(stuid int,username varchar(20),password varchar(20) ); --插入數(shù)據(jù) insert student(stuid,username,password)values ("10001","Eastmount","111111"); insert student(stuid,username,password)values ("10002","Yangxiuzhang","123456"); --顯示表結(jié)構(gòu) desc student; --查詢表中數(shù)據(jù) select * from student;? ? ? ? 其中表結(jié)構(gòu)和表中數(shù)據(jù)顯示如下圖:
三. Java代碼
? ? ? ?1.在src下新建文件夾util,然后添加類JDBCConnect.java。代碼如下:
package util;import java.sql.*; import com.mysql.jdbc.Driver;public class JDBCConnect {//獲取默認(rèn)數(shù)據(jù)庫(kù)連接public static Connection getConnection() throws SQLException {return getConnection("TestDAO", "root", "123456"); //數(shù)據(jù)庫(kù)名 默認(rèn)用戶 密碼}//連接數(shù)據(jù)庫(kù) 參數(shù):數(shù)據(jù)庫(kù)名 root登錄名 密碼public static Connection getConnection(String dbName, String userName,String password) throws SQLException {String url = "jdbc:mysql://localhost:3306/" + dbName + "?characterEncoding=utf-8";//連接MySQL"com.mysql.jdbc.Driver"DriverManager.registerDriver(new Driver());return DriverManager.getConnection(url, userName, password);}//設(shè)置 PreparedStatement 參數(shù) public static void setParams(PreparedStatement preStmt, Object... params)throws SQLException {if (params == null || params.length == 0)return;for (int i = 1; i <= params.length; i++) {Object param = params[i - 1];if (param == null) {preStmt.setNull(i, Types.NULL);} else if (param instanceof Integer) {preStmt.setInt(i, (Integer) param);} else if (param instanceof String) {preStmt.setString(i, (String) param);} else if (param instanceof Double) {preStmt.setDouble(i, (Double) param);} else if (param instanceof Long) {preStmt.setDouble(i, (Long) param);} else if (param instanceof Timestamp) {preStmt.setTimestamp(i, (Timestamp) param);} else if (param instanceof Boolean) {preStmt.setBoolean(i, (Boolean) param);} else if (param instanceof Date) {preStmt.setDate(i, (Date) param);}}}//執(zhí)行 SQL,返回影響的行數(shù) 異常處理public static int executeUpdate(String sql) throws SQLException {return executeUpdate(sql, new Object[] {});}//帶參數(shù)執(zhí)行SQL,返回影響的行數(shù) 異常處理public static int executeUpdate(String sql, Object... params)throws SQLException {Connection conn = null;PreparedStatement preStmt = null;try {conn = getConnection();preStmt = conn.prepareStatement(sql);setParams(preStmt, params);return preStmt.executeUpdate(); //執(zhí)行SQL操作} finally {if (preStmt != null)preStmt.close();if (conn != null)conn.close();}} }
? ? ? ?其中主要是調(diào)用getConnection(url,?userName,?password); 方法進(jìn)行連接數(shù)據(jù)庫(kù)操作,我數(shù)據(jù)庫(kù)的名稱為TestDAO,默認(rèn)的連接對(duì)象為root,密碼為123456。同時(shí)定義兩個(gè)函數(shù)執(zhí)行無(wú)參數(shù)的SQL語(yǔ)句操作和有參數(shù)的SQL語(yǔ)句操作。
? ? ? ?2.在src下新建文件夾bean,然后添加類Student.java。代碼如下:
package bean;public class Student {private Integer id; //學(xué)號(hào)private String name; //姓名private String password; //密碼public Integer getId() { return id; }public String getName() { return name; }public String getPassword() { return password; }public void setId(Integer id) { this.id = id; }public void setName(String name) { this.name = name; }public void setPassword(String pwd) { this.password = pwd; } }? ? ? ? 該Student中的變量及類型與數(shù)據(jù)庫(kù)中一一對(duì)應(yīng),在通過get和set方法獲取和設(shè)置其值。同樣如果你的數(shù)據(jù)庫(kù)中有老師、學(xué)校表,你只需要在bean文件夾下添加Teacher.java和School.java即可。
? ? ? ? 3.在src下新建文件夾DAO,然后添加類StudentDAO.java。代碼如下:
package DAO;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;import bean.Student; import util.JDBCConnect;public class StudentDAO {//插入學(xué)生public static int insert(Student stu) throws Exception {String sql = "INSERT INTO student (stuid,username,password) VALUES (?,?,?) ";return JDBCConnect.executeUpdate(sql, stu.getId(),stu.getName(),stu.getPassword());}//更新學(xué)生姓名public static int update(Student stu) throws Exception {String sql = "UPDATE student SET stuid = ? WHERE username = ? ";return JDBCConnect.executeUpdate(sql,stu.getId(),stu.getName());}//刪除操作public static int delete(Integer id) throws Exception {String sql = "DELETE FROM student WHERE stuid = ? ";return JDBCConnect.executeUpdate(sql, id);}//查找記錄 某學(xué)號(hào)public static Student find(Integer id) throws Exception {String sql = "SELECT * FROM student WHERE stuid = ? ";Connection conn = null;PreparedStatement preStmt = null;ResultSet rs = null;try {//鏈接數(shù)據(jù)庫(kù)執(zhí)行SQL語(yǔ)句conn = JDBCConnect.getConnection(); //連接默認(rèn)數(shù)據(jù)庫(kù)preStmt = conn.prepareStatement(sql);preStmt.setInt(1, id);rs = preStmt.executeQuery();//獲取查詢結(jié)果if (rs.next()) {Student student = new Student();student.setId(rs.getInt("stuid"));student.setName(rs.getString("username"));return student;} else {return null;}} finally { //依次關(guān)閉 記錄集 聲明 連接對(duì)象if (rs != null)rs.close();if (preStmt != null)preStmt.close();if (conn != null)conn.close();}}//查詢所有學(xué)生信息public static List<Student> listStudents() throws Exception {List<Student> list = new ArrayList<Student>();String sql = "SELECT * FROM student";Connection conn = null;PreparedStatement preStmt = null;ResultSet rs = null;try {conn = JDBCConnect.getConnection();preStmt = conn.prepareStatement(sql);rs = preStmt.executeQuery();while (rs.next()) {//設(shè)置數(shù)據(jù)庫(kù)中表參數(shù) 否則報(bào)錯(cuò)java.sql.SQLException: Column 'id' not found.Student student = new Student();student.setId(rs.getInt("stuid")); student.setName(rs.getString("username"));student.setPassword(rs.getString("password"));list.add(student);}} finally {if (rs != null)rs.close();if (preStmt != null)preStmt.close();if (conn != null)conn.close();}return list;}} ? ? ? ? 通常DAO(Data Access Object)數(shù)據(jù)訪問對(duì)象是負(fù)責(zé)與數(shù)據(jù)庫(kù)連接,主要功能執(zhí)行對(duì)數(shù)據(jù)表的CUDR操作。? ? ? ? C(Create)操作:創(chuàng)建記錄,執(zhí)行insert into語(yǔ)句;
? ? ? ? U(Update)操作:業(yè)務(wù)表中對(duì)應(yīng)的屬性進(jìn)行更新操作,執(zhí)行update語(yǔ)句;
? ? ? ? D(Delete)操作:將DTO對(duì)象對(duì)應(yīng)的記錄刪除,執(zhí)行delete語(yǔ)句;
? ? ? ? R(Read)操作:讀取表中數(shù)據(jù),可以返回多個(gè)記錄列表對(duì)應(yīng)DTO對(duì)象多個(gè)List容器。
? ? ? ? 最初同學(xué)建議弄這個(gè),不敢接觸擔(dān)心很復(fù)雜,但用完后才知道它并不需要導(dǎo)入如何jar包、配置web.xml或安裝什么軟件,只需通過DAO接口實(shí)現(xiàn)DAO對(duì)象的CUDR操作。
? ? ? ? 每個(gè)數(shù)據(jù)表都定義一個(gè)DAO接口或類實(shí)現(xiàn),實(shí)現(xiàn)對(duì)此表的讀寫操作。換句話說(shuō),就是在域名.項(xiàng)目.模塊.dao文件夾下創(chuàng)建個(gè)DAO類即可。
? ? ? ? 例如“package com.neusoft.dao;”
?
四. Jsp代碼
? ? ? ? 然后是WebRoot文件夾下的jsp代碼。其中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>This is my JSP page. <br><A href="student.jsp">JDBC操作</A></body> </html>
? ? ? ? 然后點(diǎn)擊JDBC操作跳轉(zhuǎn)到student.jsp操作,代碼如下:涉及EL和JSTL。
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <jsp:directive.page import="DAO.StudentDAO"/> <jsp:directive.page import="java.util.List"/> <%List studentList = StudentDAO.listStudents();request.setAttribute("studentList", studentList); %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>My JSP 'student.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"><style type="text/css">body, td, th, input {font-size:12px; text-align:center; }</style></head><body><form action="operateStudent.jsp" method=get><table bgcolor="#CCCCCC" cellspacing=1 cellpadding=5 width=100%><tr bgcolor=#DDDDDD><th>選擇</th><th>學(xué)號(hào)</th><th>姓名</th><th>密碼</th><th>操作</th></tr><c:forEach items="${studentList}" var="stu"><tr bgcolor="#FFFFFF"><td><input type="checkbox" name="id" value="${stu.id}" /></td><td>${stu.id}</td><td>${stu.name}</td><td>${stu.password}</td><td><a href="addEmployee.jsp?action=edit&id=${stu.id}">修改</a><a href="addEmployee.jsp?action=del&id=${stu.id}" οnclick="return confirm('確定刪除?')">刪除</a></td></tr></c:forEach></table></form></body> </html>
? ? ? ? 文章運(yùn)行結(jié)果如下圖所示:
? ? ? ? 最后總結(jié)下,文章主要講述了如何通過DAO和Java Bean實(shí)現(xiàn)Java數(shù)據(jù)庫(kù)操作、界面顯示分離的操作;同樣的道理,實(shí)現(xiàn)修改、刪除、插入方法類似,后面可能會(huì)講述。該方法主要是通過上一篇自己的體會(huì),找到的解決辦法。最后希望文章對(duì)你有所幫助,如果有錯(cuò)誤或不足之處,還請(qǐng)海涵~
? ? ? ? 最重要的一個(gè)問題,在這過程中你可能會(huì)遇到以下兩個(gè)錯(cuò)誤:(困擾我4小時(shí))
? ? ? ??Servlet.service() for servlet [jsp] in context with path?
? ? ? ??javax.el.PropertyNotFoundException: Property 'id' not found on type bean.Student
? ? ? ? 其解決方案參考:http://blog.csdn.net/eastmount/article/details/45835481
? ? ? ?(By:Eastmount 2015-5-19 凌晨2點(diǎn) ??http://blog.csdn.net/eastmount/)
? ? ? ??
總結(jié)
以上是生活随笔為你收集整理的Java+MyEclipse+Tomcat (五)DAO和Java Bean实现数据库和界面分开操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [python学习] 模仿浏览器下载CS
- 下一篇: java美元兑换,(Java实现) 美元