DAO(数据访问对象)设计模式——JSP的应用(使用PostgreSQL数据库)
程序员文章站
2022-06-04 08:39:17
DAO(数据访问对象) 程序的标准架构为: 客户层(Client)-> 显示层(jsp/servlet)-> 业务层(BO) → 数据层(BAO) → 资源层(DataBase) 项目Gitee地址:https://gitee.com/hcflyambation/daoproject 1,组成部分( ......
dao(数据访问对象)
程序的标准架构为:
客户层(client)-> 显示层(jsp/servlet)-> 业务层(bo) -> 数据层(bao) -> 资源层(database)
项目gitee地址:
1,组成部分(java命名规范)
- 1,databaseconnection: 专门负责数据库打开和关闭操作的类;(xxx.dbc.databaseconnection)
- 2,vo:主要由属性、setter、geter组成,vo类中的属性与表中的字段相对应。(xxx.vo.xxx)
- 3,dao: 主要定义操作的接口,定义一系列的数据库的原子性操作,如,增删改查。(xxx.dao.xxxdao)
- 4,impl:dao接口的真实实现类,完成具体的数据库操作,但是不负责数据库的打开和关闭。(xxx.dao.impl.xxxdaoimpl)
- 5,proxy:代理实现类,主要完成数据库的打开和关闭,并且调用真实实现类对象的操作。(xxx.dao.proxy.xxxdaoproxy)
- 6,factory:工厂类,通过工厂类获得一个dao的实例化对象。(xxx.factory.daofactory)
2,dao的实例开发
项目结构:
特别要注意的是:当启动web程序时,请将依赖的jar(postgresql-42.2.19.jar放入web-inf/lib/下,不然会检测不到)
jar必须直接放在web项目的/ web-inf / lib文件夹中,而不用项目属性中的build path.该文件夹是webapp运行时类路径的标准部分
2.1,数据库脚本建立(使用postgresql)
数据库名为:jsp
create table emp ( empno int primary key, ename varchar(10), job varchar(9), hiredate date, sal decimal );
2.2,编写与数据库对应的ov类(emp.java)
package com.hcfly.vo; import java.math.bigdecimal; import java.util.date; public class emp { private int empno; private string ename; private string job; private date hiredate; private float sal; public int getempno() { return empno; } public void setempno(int empno) { this.empno = empno; } public string getename() { return ename; } public void setename(string ename) { this.ename = ename; } public string getjob() { return job; } public void setjob(string job) { this.job = job; } public date gethiredate() { return hiredate; } public void sethiredate(date hiredate) { this.hiredate = hiredate; } public float getsal() { return sal; } public void setsal(float sal) { this.sal = sal; } }
2.3, 编写数据库连接类(databaseconnection.java)
这个地方可以将databaseconnection抽象为一个接口,并且用不同的数据库访问类去实现它,来达到通用的水平。
package com.hcfly.dbc; import java.sql.connection; import java.sql.drivermanager; public class databaseconnection { // 数据库连接类 private static final string dbdriver = "org.postgresql.driver"; private static final string dburl = "jdbc:postgresql://localhost/jsp"; private static final string dbuser = "postgres"; private static final string dbpassword = "miaomiao"; private connection connection = null; public databaseconnection() throws exception{ try { class.forname(dbdriver); this.connection = drivermanager.getconnection(dburl, dbuser, dbpassword); // system.out.println("连接成功"); } catch (exception e) { throw e; // todo: handle exception } } public connection getconnection() { return this.connection; } public void close() throws exception { if(this.connection != null) { try { this.connection.close(); } catch (exception e) { throw e; // todo: handle exception } } } }
2.4,定义dao操作标准(iempdao.java)
package com.hcfly.dao; import java.util.list; import com.hcfly.vo.emp; public interface iempdao { // 定义dao操作 /** * 定义dao的标准操作 * */ public boolean docreate(emp emp) throws exception; /** * @param emp要增加的数据对象 */ public list<emp> findall(string keyword) throws exception; /** * 根据查询关键字进行搜索 */ public emp findbyid(int empno) throws exception; }
2.5,真实主题实现类(empdaoimpl.java)
package com.hcfly.dao.impl; import java.sql.connection; import java.sql.date; import java.sql.preparedstatement; import java.sql.resultset; import java.util.arraylist; import java.util.list; import com.hcfly.dao.iempdao; import com.hcfly.vo.emp; public class empdaoimpl implements iempdao{ /** * 真实主题类 */ private connection connection = null; private preparedstatement pstmt = null; public empdaoimpl(connection connection) { // 获取数据库连接 this.connection = connection; } @override public boolean docreate(emp emp) throws exception { boolean flag = false; string sql = "insert into emp (empno, ename, job, hiredate, sal) values (?,?,?,?,?)"; this.pstmt = this.connection.preparestatement(sql); this.pstmt.setint(1, emp.getempno()); this.pstmt.setstring(2, emp.getename()); this.pstmt.setstring(3, emp.getjob()); this.pstmt.setdate(4, new date(emp.gethiredate().gettime())); this.pstmt.setfloat(5, emp.getsal()); if(this.pstmt.executeupdate() > 0) { // 更新记录行数大于1 flag = true; } this.pstmt.close(); return flag; } @override public list<emp> findall(string keyword) throws exception { list<emp> all = new arraylist<emp>(); string sql = "select empno, ename, job, hiredate, sal from emp where ename like ? or job like ?"; this.pstmt = this.connection.preparestatement(sql); this.pstmt.setstring(1, "%"+keyword +"%"); this.pstmt.setstring(2, "%"+keyword +"%"); resultset rset = this.pstmt.executequery(); emp emp = null; while (rset.next()) { emp = new emp(); emp.setempno(rset.getint("empno")); emp.setename(rset.getstring("ename")); emp.sethiredate(rset.getdate("hiredate")); emp.setjob(rset.getstring("job")); emp.setsal(rset.getfloat("sal")); all.add(emp); } this.pstmt.close(); // todo auto-generated method stub return all; } @override public emp findbyid(int empno) throws exception { string sql = "select empno, ename, job, hiredate, sal from emp where empno=?"; this.pstmt = this.connection.preparestatement(sql); this.pstmt.setint(1, empno); resultset rset = this.pstmt.executequery(); emp emp = null; if(rset.next()) { emp = new emp(); emp.setempno(rset.getint("empno")); emp.setename(rset.getstring("ename")); emp.sethiredate(rset.getdate("hiredate")); emp.setjob(rset.getstring("job")); emp.setsal(rset.getfloat("sal")); } this.pstmt.close(); // todo auto-generated method stub return emp; } }
2.5,代理主题实现类(iempdaoproxy.java)
package com.hcfly.dao.proxy; import java.util.list; import com.hcfly.dao.iempdao; import com.hcfly.dao.impl.empdaoimpl; import com.hcfly.dbc.databaseconnection; import com.hcfly.vo.emp; public class empdaoproxy implements iempdao{ /** * 代理主题实现类 */ private databaseconnection dbc = null; private iempdao dao = null; public empdaoproxy() throws exception{ this.dbc = new databaseconnection(); // 连接到数据库 this.dao = new empdaoimpl(this.dbc.getconnection()); } @override public boolean docreate(emp emp) throws exception { boolean flag = false; try { if(this.dao.findbyid(emp.getempno()) == null) { flag = this.dao.docreate(emp); } } catch (exception e) { throw e; }finally { this.dbc.close(); // 无论是否成功,将连接关闭 } // todo auto-generated method stub return flag; } @override public list<emp> findall(string keyword) throws exception { list<emp> all = null; try { all = this.dao.findall(keyword); } catch (exception e) { throw e; } finally { this.dbc.close(); } return all; } @override public emp findbyid(int empno) throws exception { emp emp = null; try { emp = this.dao.findbyid(empno); } catch (exception e) { throw e; }finally { this.dbc.close(); } return emp; } }
2.6,dao工厂类(daofactory.java)
package com.hcfly.factory; import com.hcfly.dao.iempdao; import com.hcfly.dao.proxy.empdaoproxy; public class daofactory { /** * 工厂类 * @return * @throws exception */ public static iempdao getiempdaoinstance() throws exception{ return new empdaoproxy(); } }
2.7,测试类(testdaoinsert.java)
package com.hcfly.dao.test; import java.util.date; import com.hcfly.factory.daofactory; import com.hcfly.vo.emp; public class testdaoinsert { public static void main(string[] args) throws exception{ // todo auto-generated method stub emp emp = null; for(int x = 0; x < 5; x++) { emp = new emp(); emp.setempno(1000+x); emp.setename("张憨憨" + x); emp.setjob("程序员 - " + x); emp.sethiredate(new date()); emp.setsal(500 * x); // daofactory.getiempdaoinstance().docreate(emp); } system.out.println(daofactory.getiempdaoinstance().findbyid(1001)); } }
2.8,总结
dao 只是提供了一个数据的操作平台,不管在application还是web程序中,此dao程序都不用做修改。
3,dao的web使用实例(开发工具为ecplise,如果要运行,请先配置数据库)
从注册页面提交信息给数据库,然后读出来,展示到表格中。
3.1, 登录注册页面(增加数据表单)(emp_insert.jsp)
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>注册</title> </head> <body> <form action="emp_insert_do.jsp" method="post" > 雇员编号:<input type="text" name="empno" id=""><br/> 雇员姓名:<input type="text" name="ename" id=""><br/> 雇员职位:<input type="text" name="job" id=""><br/> 雇员日期:<input type="text" name="hiredate" id=""><br/> 雇员工资:<input type="text" name="sal" id=""><br/> <input type="submit" value="注册"> <input type="reset" value="重置"> </form> <a href="emp_list.jsp">跳转到列表页面</a> </body> </html>
3.2, 处理数据页面(emp_insert_do.jsp)
<%@page import="com.hcfly.factory.daofactory"%> <%@page import="java.text.simpledateformat"%> <%@page import="com.hcfly.vo.emp"%> <%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title>处理表单</title> <%request.setcharacterencoding("utf-8"); response.setheader("refresh", "3;url=emp_list.jsp"); // 设置跳转时间为3秒 %> </head> <body> <% emp emp = new emp(); emp.setempno(integer.parseint(request.getparameter("empno"))); emp.setename(request.getparameter("ename")); emp.setjob(request.getparameter("job")); emp.sethiredate(new simpledateformat("yyyy-mm-dd").parse(request.getparameter("hiredate"))); emp.setsal(float.parsefloat(request.getparameter("sal"))); try{ if(daofactory.getiempdaoinstance().docreate(emp)){ out.print("<h3>雇员信息添加成功!</h3>"); }else{ out.print("<h3>雇员信息添加失败!</h3>"); } }catch(exception e){ e.printstacktrace(); } %> <h3>3秒后跳转到列表页</h3> </body> </html>
3.3,列表页面(emp_list.jsp)
<%@page import="com.hcfly.vo.emp"%> <%@page import="java.util.list"%> <%@page import="org.apache.jasper.tagplugins.jstl.core.catch"%> <%@page import="java.util.iterator"%> <%@page import="com.hcfly.factory.daofactory"%> <%@page import="java.util.dictionary"%> <%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title>列表</title> <% request.setcharacterencoding("utf-8"); %> </head> <body> <% try{ string keyword = request.getparameter("kw"); if(keyword == null){ keyword = ""; } list<emp> all = daofactory.getiempdaoinstance().findall(keyword); iterator<emp> iter = all.iterator(); %> <center> <form action="" method="post"> <input type="text" name="kw"> <input type="submit" value="查询"> </form> <table border="1" width="80%"> <tr> <td>雇员编号:</td> <td>雇员姓名:</td> <td>雇员工作:</td> <td>雇员工资:</td> <td>雇员日期:</td> </tr> <% while(iter.hasnext()){ emp emp = iter.next(); %> <tr> <td><%= emp.getempno() %></td> <td><%= emp.getename() %></td> <td><%= emp.getjob() %></td> <td><%= emp.getsal() %></td> <td><%= emp.gethiredate() %></td> </tr> <% } %> </table> <a href="emp_insert.jsp">跳转到插入页面</a> </center> <% }catch(exception e){ e.printstacktrace(); } %> </body> </html>
3.4,结果展示
3.4.1 数据库
3.4.2,注册界面
3.4.3,列表页面
上一篇: 设计模式—singleton(单例模式)
下一篇: c#金额转换成中文大写金额