Servlet + JavaBean + Jdbc.docx
- 文档编号:18533030
- 上传时间:2023-08-19
- 格式:DOCX
- 页数:15
- 大小:18.67KB
Servlet + JavaBean + Jdbc.docx
《Servlet + JavaBean + Jdbc.docx》由会员分享,可在线阅读,更多相关《Servlet + JavaBean + Jdbc.docx(15页珍藏版)》请在冰点文库上搜索。
Servlet+JavaBean+Jdbc
Servlet+JavaBean+Jdbc
一.JavaBean2
1.1JavaBean简介2
1.2JavaBean用途2
1.3JavaBean实例2
二.JDBC3
三.Dao4
四.Service6
五.Servlet8
六.架构改进9
6.1JDBC多事务处理9
6.2JDBC增删改的通用方法9
6.3JDBC查询的通用方法10
6.4Connection连接优化13
6.5Statement优化14
6.6PreparedStatement优化14
1.JavaBean
1.1JavaBean简介
领域对象层的JavaBean一般与数据库表相对应,包含一系列私有属性和操作这些属性的公共的set()、get()方法。
一般都提供公共的无参的构造方法。
1.2JavaBean用途
使用JDBC操作数据库时,将JavaBean对象转换为数据库字段—插入修改操作,或将JavaBean对象属性添加到Sql语句中执行—插入删除修改查询操作,或将查询得到的数据库字段封装为JavaBean对象—查询操作,以此完成面向对象和关系数据库的转换。
1.3JavaBean实例
//User
packagetxazo.domain;
publicclassUser{
privateIntegerid;
privateStringusername;
privateStringpassword;
publicUser(){
}
publicUser(Stringusername,Stringpassword){
this.username=username;
this.password=password;
}
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
}
2.JDBC
获取数据库连接Connection。
//ConnectionUtil
packagetxazo.util;
publicclassConnectionUtil{
publicstaticStringDRIVER="com.mysql.jdbc.Driver";
publicstaticStringURL="jdbc:
mysql:
//127.0.0.1:
3306/txazo";
publicstaticStringUSER="root";
publicstaticStringPASSWORD="root";
publicstaticConnectiongetConnection(){
Connectionconnection=null;
try{
Class.forName(DRIVER);
connection=DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exceptione){
e.printStackTrace();
}
returnconnection;
}
}
3.Dao
打开Connection连接后,通过JDBCAPI操作数据库,然后对外提供创建Dao接口的工厂。
//UserDao
packagetxazo.dao;
publicinterfaceUserDao{
publicvoidsave(Useruser);
publicvoiddelete(Useruser);
publicvoiddelete(Integerid);
publicvoidupdate(Useruser);
publicUserget(Integerid);
}
//UserDaoImpl
packagetxazo.dao.impl;
publicclassUserDaoImplimplementsUserDao{
privateConnectionconnection=null;
privatePreparedStatementpreparedStatement=null;
@Override
publicvoidsave(Useruser){
connection=ConnectionUtil.getConnection();
try{
connection.setAutoCommit(false);
preparedStatement=connection
.prepareStatement("insertintouser(username,password)values(?
?
)");
preparedStatement.setString(1,user.getUsername());
preparedStatement.setString(2,user.getPassword());
preparedStatement.executeUpdate();
mit();
}catch(Exceptione){
e.printStackTrace();
try{
connection.rollback();
}catch(Exceptione1){
e1.printStackTrace();
}
}finally{
try{
if(preparedStatement!
=null)
preparedStatement.close();
if(connection!
=null)
connection.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
}
//DaoFactory
packagetxazo.dao.factory;
publicclassDaoFactory{
publicstaticUserDaogetUserDao(){
returnnewUserDaoImpl();
}
}
4.Service
通过Dao接口的工厂获取Dao,调用Dao进行业务逻辑处理,然后对外提供创建Service接口的工厂。
//UserService
packagetxazo.service;
publicinterfaceUserService{
publicvoidsave(Useruser);
publicvoiddelete(Useruser);
publicvoiddelete(Integerid);
publicvoidupdate(Useruser);
publicUserget(Integerid);
}
//UserServiceImpl
packagetxazo.service.impl;
publicclassUserServiceImplimplementsUserService{
@Override
publicvoiddelete(Useruser){
DaoFactory.getUserDao().delete(user);
}
@Override
publicvoiddelete(Integerid){
DaoFactory.getUserDao().delete(id);
}
@Override
publicUserget(Integerid){
returnDaoFactory.getUserDao().get(id);
}
@Override
publicvoidsave(Useruser){
DaoFactory.getUserDao().save(user);
}
@Override
publicvoidupdate(Useruser){
DaoFactory.getUserDao().update(user);
}
}
//ServiceFactory
packagetxazo.service.factory;
publicclassServiceFactory{
publicstaticUserServicegetUserService(){
returnnewUserServiceImpl();
}
}
5.Servlet
处理页面请求。
解析请求参数,通过Service接口的工厂获取Service,调用Service进行处理,然后跳转到指定页面。
//UserServlet
packagetxazo.servlet;
publicclassUserServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
super.doPost(req,resp);
}
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
Stringusername=req.getParameter("username");
Stringpassword=req.getParameter("password");
Useruser=newUser(username,password);
ServiceFactory.getUserService().save(user);
req.getRequestDispatcher("/home.jsp").forward(req,resp);
}
}
6.架构改进
6.1JDBC多事务处理
在Dao中打开和关闭Connection连接,事务局限于Dao方法,在Service中涉及多事务处理会发生数据库不一致的现象。
为了可以支持多事务处理,可以在Service中打开和关闭Connection连接,然后将Connection对象传入到Dao中即可。
这样就可以在Service中统一处理业务逻辑,多个事务统一提交或回滚。
6.2JDBC增删改的通用方法
JDBC增删改操作不需要返回数据,只需要相应Sql语句和参数即可,因此可以将增删改操作合并为一个通用的方法。
//BaseDao
packagetxazo.dao;
publicinterfaceBaseDao{
publicvoidexecuteUpdate(Stringsql,Object[]params);
}
//BaseDaoImpl
packagetxazo.dao.impl;
publicclassBaseDaoImplimplementsBaseDao{
privateConnectionconnection=null;
privatePreparedStatementpreparedStatement=null;
@Override
publicvoidexecuteUpdate(Stringsql,Object[]params){
connection=ConnectionUtil.getConnection();
try{
connection.setAutoCommit(false);
preparedStatement=connection.prepareStatement(sql);
for(inti=0;i preparedStatement.setObject(i+1,params[i]); } preparedStatement.executeUpdate(); mit(); }catch(Exceptione){ e.printStackTrace(); try{ connection.rollback(); }catch(Exceptione1){ e1.printStackTrace(); } }finally{ try{ if(preparedStatement! =null) preparedStatement.close(); if(connection! =null) connection.close(); }catch(Exceptione){ e.printStackTrace(); } } } } 6.3JDBC查询的通用方法 不同的JDBC查询会返回不同的结果集,为了统一查询方法,结合泛型和反射,可以将查询的结果集封装为JavaBean对象,添加到List集合中。 为了支持JDBC的通用查询方法,JavaBean对象的属性必须和查询结果集的字段一一对应,同时提供set()、get()方法和公共的无参的构造方法。 //BaseDao packagetxazo.dao; publicinterfaceBaseDao{ public Object[]params); } //BaseDaoImpl packagetxazo.dao.impl; publicclassBaseDaoImplimplementsBaseDao{ privateConnectionconnection=null; privatePreparedStatementpreparedStatement=null; privateResultSetresultSet=null; @Override public Object[]params){ List connection=ConnectionUtil.getConnection(); try{ connection.setAutoCommit(false); preparedStatement=connection.prepareStatement(sql); for(inti=0;i preparedStatement.setObject(i+1,params[i]); } resultSet=preparedStatement.executeQuery(); list=getResultList(objectClass,resultSet); mit(); returnlist; }catch(Exceptione){ e.printStackTrace(); try{ connection.rollback(); }catch(Exceptione1){ e1.printStackTrace(); } }finally{ try{ if(preparedStatement! =null) preparedStatement.close(); if(connection! =null) connection.close(); }catch(Exceptione){ e.printStackTrace(); } } returnnull; } private List try{ Field[]fields=objectClass.getDeclaredFields(); Map for(inti=0;i StringfieldName=fields[i].getName(); StringfirstLetter=fieldName.substring(0,1).toUpperCase(); StringsetMethodName="set"+firstLetter +fieldName.substring (1); MethodsetMethod=objectClass.getMethod(setMethodName, newClass[]{fields[i].getType()}); map.put(fieldName,setMethod); } Set while(resultSet.next()){ Tobject=null; object=objectClass.getConstructor(newClass[]{}) .newInstance(newObject[]{}); for(Stringkey: keySet){ map.get(key).invoke( object, newObject[]{resultSet.getObject(key .toLowerCase())}); } list.add(object); } }catch(Exceptione){ e.printStackTrace(); } returnlist; } 6.4Connection连接优化 为提高JDBC操作数据库性能,可以使用Connection连接池,包括DBCP或C3P0。 //C3P0ConnectionPool packagetxazo.util; publicclassC3P0ConnectionPool{ privateC3P0ConnectionPool(){ } privatestaticComboPooledDataSourceds=null; static{ try{ ds=newComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc: mysql: //127.0.0.1/txazo"); ds.setUser("root"); ds.setPassword("root"); ds.setMaxPoolSize(20); ds.setMinPoolSize (2); }catch(Exceptione){ e.printStackTrace(); } } publicstaticsynchronizedConnectiongetConnection(){ Connectioncon=null; try{ con=ds.getConnection(); }catch(Exceptione){ e.printStackTrace(); } returncon; } } 6.5Statement优化 批量更新 Statementstatement=connection.createStatement(); statement.addBatch("deletefromuserwhereusername='root'"); statement.addBatch("updateusersetpassword='123456'"); statement .addBatch("insertintouser(username,password)values('tomcat','tomcat')"); statement.executeBatch(); 6.6PreparedStatement优化 批量更新 PreparedStatementpreparedStatement=
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Servlet JavaBean Jdbc
![提示](https://static.bingdoc.com/images/bang_tan.gif)