用struts开发的时候,数据库连接大家看我这样写好不好?

倪明123 2007-08-06 09:32:43
1:我看精通struts 邮电出版社的那本书的时候,讲的是使用struts-config.xml中的datasource配置数据源。
然后在每个action都写一个获得数据源 DataSource dataSource=(DataSource)this.getDataSource(request,"datasource");然后在写数据库的读取或者增加或者删除操作。最后相应的每个数据库资源的释放。代码贴出:
stuts-config.xml:
<struts-config>
<data-sources>
<data-source key="datasource" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName"
value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
<set-property property="url"
value="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=shopping"/>
<set-property property="maxActive"
value="5" />
<set-property property="username"
value="sa" />
<set-property property="password"
value="" />
<set-property property="autoCommit"
value="true" />
</data-source>
</data-sources>
.....
</struts-config>
相关的action类:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.wnkj.struts.action.corporation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.wnkj.struts.form.NewloginForm;

/**
* MyEclipse Struts
* Creation date: 07-07-2007
*
* XDoclet definition:
* @struts.action path="/newlogin" name="newloginForm" input="/form/newlogin.jsp" scope="request" validate="true"
* @struts.action-forward name="success" path="/struts/ok1.jsp"
*/
public class NewloginAction extends Action {
String howemail="@ny114.cn";
Connection con=null;
Statement stat=null;
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
NewloginForm newloginForm = (NewloginForm) form;// TODO Auto-generated method stub
String username=newloginForm.getUsername();
String psd=newloginForm.getPassword1();
String email=newloginForm.getEmail();
String standemail=username+howemail;
try{
DataSource dataSource=(DataSource)this.getDataSource(request,"datasource");
con=dataSource.getConnection();
stat=con.createStatement();
String sql="insert into t_user(f_nickName,f_password,f_email,f_regtime,f_standemail) values ('"+username+"','"+psd+"','"+email+"',getdate(),'"+standemail+"')";
int i=stat.executeUpdate(sql);
if(i>0){
request.setAttribute("insert", sql);
HttpSession session=request.getSession();
session.setAttribute("username", username);

}
else{
request.setAttribute("error", sql);
}
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
if(con!=null){
try{
con.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
close();
}
return mapping.findForward("success");
}

public void close(){
try{
if(stat!=null){
try{
stat.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
catch(Exception ex){
ex.printStackTrace();
}

}
}
以上是第一种方法,下面是第二种方法。


见下帖:

...全文
395 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
凄凄迷人 2007-08-11
  • 打赏
  • 举报
回复
看 bitter java 里有这方面的说明.
ziyu_1 2007-08-10
  • 打赏
  • 举报
回复
太多了,为什么不用hibernate
yqh2009 2007-08-09
  • 打赏
  • 举报
回复
第一种是连接池,在连接频繁时,比第二种省内存
倪明123 2007-08-09
  • 打赏
  • 举报
回复
我说呢,我用struts开发的时候,感觉struts就是简化了操作的流程,并没有看到多少功能的强大啊!
java的核心到底是什么?
记得刚开始学习java的时候,感觉struts深不可测,现在感觉struts效率也并不是很高啊?下一步的学习应该怎么进行??
在看些哪方面的书?
livan1038 2007-08-08
  • 打赏
  • 举报
回复
連接用完之後close是要關閉,是要求也應該是習慣。struts和hibernate組合也是比較流行的做法。
freedom2001 2007-08-08
  • 打赏
  • 举报
回复
hibernate关回收什么事,难道你在用完session就不用close了吗?那还不一样的关闭连接嘛,拿hibernate比这个问题没有意义
倪明123 2007-08-07
  • 打赏
  • 举报
回复
也就是说,大部分不是单独的再用struts,而是用的struts和hibernate的组合?
qixueqi 2007-08-07
  • 打赏
  • 举报
回复
还有一种方案
就是将数据源的信息添加到tomcat下server.xml里的GlobalNamingResources
然后在tomcat启动时加载数据源
lxdhdgss 2007-08-06
  • 打赏
  • 举报
回复
为什么使用datasource不好??

还有,楼上说的使用也需要关闭,那么每进行一次操作都需要进行对数据库的打开和关闭。和第一种方法又有什么区别呢??

大家都是用的什么方法啊?
这个问题我也想知道,指点一下啊,谢谢
倪明123 2007-08-06
  • 打赏
  • 举报
回复
什么方法才是效率比较高的?敬请指点!
倪明123 2007-08-06
  • 打赏
  • 举报
回复
为什么使用datasource不好??

还有,楼上说的使用也需要关闭,那么每进行一次操作都需要进行对数据库的打开和关闭。和第一种方法又有什么区别呢??

大家都是用的什么方法啊?
kidfang 2007-08-06
  • 打赏
  • 举报
回复
datasource不好.
第二种需要显式关闭
倪明123 2007-08-06
  • 打赏
  • 举报
回复
可以看出,这个属于数据库相关操作的类。另外相应的具体操作数据库还有一个类,贴了:

package com.wnkj.dbutil;

import java.util.*;

public class DB_GuanLiMember extends Connect {
private String sql = "";

/**
* 添加一个新的职员
*
* @return
*/
public int insertinfor(String guanlinum, String memnum, String memname,
String deptnum, String guantime, String note) {
try {
sql = "insert into guanlimember(guanlinum,memnum,memname,deptnum, guantime,note) values(?,?,?,?,?,?)";
this.pst = this.con.prepareStatement(sql);
this.pst.setString(1, guanlinum);
this.pst.setString(2, memnum);
this.pst.setString(3, memname);
this.pst.setString(4, deptnum);
this.pst.setString(5, guantime);
this.pst.setString(6, note);
} catch (Exception ex) {
ex.printStackTrace();
Write(ex, this.toString());
}
return this.insert();
}

public int updateById(String guanlinum, String memnum, String memname,
String deptnum,String guantime, String note,
int id) {
try {
sql = "update guanlimember set guanlinum=?,memnum=?,memname=?,deptnum=?,guantime=?,note=? where id=?";
this.pst = this.con.prepareStatement(sql);
this.pst.setString(1, guanlinum);
this.pst.setString(2, memnum);
this.pst.setString(3, memname);
this.pst.setString(4, deptnum);
this.pst.setString(5, guantime);
this.pst.setString(6, note);
this.pst.setInt(7, id);
} catch (Exception ex) {
ex.printStackTrace();
Write(ex, this.toString());
}
return this.update();
}
/**
* 根据id删除某条记录信息
* @param id
* @return
*/
public int deleteinfor(int id)
{
try
{
sql="delete from guanlimember where id=?";
this.pst=this.con.prepareStatement(sql);
this.pst.setInt(1, id);
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
}
return this.delete();
}
/**
* 查询某一个会员的id信息
*
* @param deptnum
* @return
*/
public ArrayList selectById(int id) {
try {
sql = "select * from guanlimember where id=?";
this.pst = this.con.prepareStatement(sql);
this.pst.setInt(1, id);
} catch (Exception ex) {
ex.printStackTrace();
Write(ex, this.toString());
}
return this.select();
}

/**
* 查询某一个部门的会员信息
*
* @param deptnum
* @return
*/
public ArrayList selectByDeptNum(String deptnum) {
try {
sql = "select * from guanlimember where deptnum=?";
this.pst = this.con.prepareStatement(sql);
this.pst.setString(1, deptnum);
} catch (Exception ex) {
ex.printStackTrace();
Write(ex, this.toString());
}
return this.select();
}

/**
* 查询管理表中的所有数据信息
*
* @return
*/
public ArrayList selectAll() {
try {
sql = "select guanlimember.id,guanlinum,memnum,memname,jigou.deptnum,jigou.deptname,guantime,guanlimember.note from guanlimember,jigou where guanlimember.deptnum=jigou.deptnum";
this.pst = this.con.prepareStatement(sql);
} catch (Exception ex) {
ex.printStackTrace();
Write(ex, this.toString());
}
return this.select();
}
}

最后是相应的action类:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.wnkj.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.wnkj.dbutil.DB_GuanLiMember;
import com.wnkj.dbutil.DB_ZhangQi;
import com.wnkj.formbean.AddZhiYuanForm;

/**
* MyEclipse Struts Creation date: 05-14-2007
*
* XDoclet definition:
*
* @struts.action path="/addZhiyuan" name="addZhiyuanForm"
* input="/form/addZhiyuan.jsp" scope="request" validate="true"
*/
public class AddZhiYuanAction extends Action {
/*
* Generated Methods
*/
public static int flag = 0;

/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
AddZhiYuanForm addZhiYuanForm = (AddZhiYuanForm) form;
String guanlinum = addZhiYuanForm.getGuanlinum();
String memnum = addZhiYuanForm.getMemnum();
String memname = addZhiYuanForm.getMemname();
String deptnum = addZhiYuanForm.getDeptnum();
String guantime = addZhiYuanForm.getGuantime();
String note = addZhiYuanForm.getNote();

int row = new DB_GuanLiMember().insertinfor(guanlinum, memnum, memname,
deptnum, guantime, note);
if (row == 1) {
flag = 1;
} else {
flag = -1;
}
response.sendRedirect(request.getContextPath()+ "/nongzi/addZhiYuan.jsp");
return null;
}
}

贴码完毕,请问:在struts开发中用哪一个模式比较好?或者还有其他更优秀的做法,请大家多多指点。

以上两个代码中,我有两个地方不是很理解:
1:使用datasource配置时候,每个action都要打开-操作-关闭数据库,很繁琐。
2:在第二类代码中,已经写好try catch finally 之后是不是就不用在相关子类或者action中调用关闭方法了?

敬请高人指点,谢谢!!
倪明123 2007-08-06
  • 打赏
  • 举报
回复
2:我看别人写的还有一种方法:(代码贴出)
package com.wnkj.dbutil;

import java.util.*;
import java.sql.*;

import com.wnkj.propertites.*;
import com.wnkj.pubclass.*;

public class Connect extends WriteLog
{
public Connection con=null;
public PreparedStatement pst=null;
public ResultSet rs=null;

private ArrayList celList=null;
private ArrayList rowList=null;
private int count=0;
public Connect()
{
try
{
String strCon="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String strUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=NPK2007";
/*
GetConnect.GetConnection();
Class.forName(GetConnect.ClassConnection);
con=java.sql.DriverManager.getConnection(GetConnect.ConnectionUrl,GetConnect.uid,GetConnect.pwd);
*/
Class.forName(strCon);
con=java.sql.DriverManager.getConnection(strUrl,"npk2007","npk2007");
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
}
}
/**
* 查询信息
*/
public ArrayList select()
{
try
{
rowList=new ArrayList();
rs=pst.executeQuery();
while(rs.next())
{
celList=new ArrayList();
for(int i=1;i<=rs.getMetaData().getColumnCount();i++)
{
celList.add(rs.getString(i)+"");
}
rowList.add(celList);
}

}catch(Exception ex)
{
ex.printStackTrace();
Write(ex, this.toString());
} finally {
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Write(e, this.toString());
}
}
return rowList;
}
/**
* 查询信息记录数
* @return
*/
public int selectCount()
{
try
{
rowList=new ArrayList();
rs=pst.executeQuery();
if(rs.next())
{
count=rs.getInt(1);
}
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex, this.toString());
} finally {
try {
if (rs != null)
rs.close();
if (pst != null)
pst.close();
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Write(e, this.toString());
}
}
return count;
}
/**
* 添加一条新的信息
* @return
*/
public int insert()
{
try
{
count=this.pst.executeUpdate();
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
} finally {
try {
if (pst != null)
pst.close();
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Write(e, this.toString());
}
}
return count;
}
/**
* 更新表中的数据
* @return
*/
public int update()
{
try
{
count=this.pst.executeUpdate();
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
} finally {
try {
if (pst != null)
pst.close();
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Write(e, this.toString());
}
}
return count;
}
/**
* 删除表中的数据
* @return
*/
public int delete()
{
try
{
count=this.pst.executeUpdate();
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
} finally {
try {
if (pst != null)
pst.close();
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Write(e, this.toString());
}
}
return count;
}
/**
* 关闭数据库连接
*
*/
public void close()
{
try
{
if(this.con!=null)
{
con.close();
}
}catch(Exception ex)
{
ex.printStackTrace();
Write(ex,this.toString());
}
}
}

未完,下帖:相应的action类
ZW_Ren 2007-08-06
  • 打赏
  • 举报
回复
下贴呢?
怎么没了
weihaiw 2007-08-06
  • 打赏
  • 举报
回复
有人测试datasource占用资源比用java bean的要多.灵活性也没有自己写的bean功能强(那当然是高手写的).
为了解决这个问题,就引入了持久层的解决方案,就是引入hibernate.主要就是资源的重复得用,以及费物回收问题.

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧