从零开始创建基于struts1.2 + Hibernate3.0 Web工程(第二部分)

来源:互联网 发布:埃迪 琼斯数据 编辑:程序博客网 时间:2024/04/28 03:05

5. 调试工程

如果本地机器已经安装了Tomcat5,那么可以在MyEclilpse的环境下调试工程了。

指定Tomcat5 的web application service 如下图:

将Enable选项打开,并且指定Tomcat的安装目录。

配置目前的工程到Tomcat中去。

点选工具栏上的被红线圈出的按钮

在弹出来的对话框中选择,我们创建的工程,和添加Tomcat5 的web application service

然后就可以按下工具栏上的启动服务按钮,调试这个Web工程了。

每一次改动工程中的文件后,要想看看改动后的效果,那么就在配置工程中,重新发布这个工程到tomecat5去。

6. Tomcat下如何配置mysql的数据库连接池

6.1 配置server.xml

配置Tomcat的server.xml文件,路径:【TOMCAT_HOME】/common/lib下的server.xml文件在</host>之前加入以下内容以添加JNDI数据源:

<taglib>
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value> </value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<parameter>
<name>url</name> <value>jdbc:mysql://192.168.0.208:3306
/db_test_account?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>

注意:

*其中蓝色字体表示你这个应用的路径和别名,也就是你访问自己配置的这个web站点的名字,注意区分大小写,必须一致,否则系统无法正常运行(例:http://localhost:8080/DBTest)

*其中红色字体表示数据源的名字,注意将会被web.xml和你访问数据库的程序调用

6.2 配置web.xml

配置Web用程序的web.xml文件

<taglib>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

6.3 访问数据库的程序片段

<taglib>
package swt.db.DBUtility;

import javax.naming.*;
import javax.sql.*;
import java.sql.*;

public class DBTest {

String foo = "Not Connected";
int bar = -1;

public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
" select UserName from t_account ");
if(rst.next()) {
foo=rst.getString(1);
bar=208;
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}

6.4 Jsp页面(index.jsp)

<taglib>
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import ="swt.db.DBUtility.*" %>
<html>
<head>
<title>DB Test</title>
</head>
<body>
<%
DBTest tst = new DBTest();
tst.init();
%>
<h2>Results</h2>
Foo <%= tst.getFoo() %><br>
Bar <%= tst.getBar() %>
</body>
</html>

启动Tomcat在浏览器上输入http://localhost:8080/DBTest

备注:

连接池配置(Database Connection Pool (DBCP) Configurations)
DBCP使用的是Jakarta-Commons Database Connection Pool 要使用连接池需要如下的组件即jar文件

Jakarta-Commons DBCP 1.1 对应commons-dbcp-1.1.jar。
Jakarta-Commons Collections 2.0 对应commons-collections.jar。
Jakarta-Commons Pool 1.1 对应commons-pool-1.1.jar。
这三个jar文件要与你的JDBC驱动程序一起放到【TOMCAT_HOME】/common/lib目录下以便让tomcat和你的web应用都能够找到。

7. Tomcat5.0下配置Hibernate3.0应用

7.1 在Tomcat下建立数据库连接池,如6中所示

7.2 在Struts应用中添加Hibernate3.0支持

注意:hibernate.cfg.xml文件一定要存放到跟目录下,默认的也就是/web应用/src,这个部署这个应用的时候hibernate.cfg.xml才会出现在classes目录下,也就是hibernate存放配置文件的默认录入下.

由于我们采用Tomcat提供的数据库连接池,所以这里我们将是用自己创建的SessionFactory类。点击完成MyEclipse会自动把 Hibernate所需的的类库加入到当前应用中。接下来就是配置Hibernate连接数据库的所需的参数,以及性能参数(可选)。

既然我们选用应用服务器所提供的数据库连接池,那么在这里我们只须要指定数据源的名字:java:comp/env/jdbc/TestDB,其中 jdbc/TestDB就是我们在Tomcat中配置的数据源,也就是我们上面提到的jdbc/TestDB,资源名称一定要匹配。其他的参数由于已经在 Tomcat中配置过了,所以在这里就不用配置了,Dialect一定要指定跟我们数据库匹配的语言。 既然我们选用应用服务器所提供的数据库连接池,那么在这里我们只须要指定数据源的名字:java:comp/env/jdbc/TestDB,其中 jdbc/TestDB就是我们在Tomcat中配置的数据源,也就是我们上面提到的jdbc/TestDB,资源名称一定要匹配。其他的参数由于已经在 Tomcat中配置过了,所以在这里就不用配置了,Dialect一定要指定跟我们数据库匹配的语言。

我们可以在这里配置Hibernate一些调整性能的参数(针对不同的数据库有些属性可能无效)。

在这里我们设置show_sql为true,这样在开发调试过程成控制台可以打印真正在数据库端执行的sql语句便于查找问题。其他一些属性可以参阅http://www.hibernate.org。
到这里Hibernate的配置已经基本完成,下面创建SessionFactory用来和数据库进行交互(Hibernate官方文档提供)。

package com.db;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static Log log =
LogFactory.getLog(HibernateUtil.class);

private static final SessionFactory sessionFactory;

static {
try {
sessionFactory = new Configuration().configure().
buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory
creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() {
Session s = (Session) session.get();
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}

public static void closeSession() {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}

后面将会提到如何使用HibernateUtil,下面建立我们所需的数据库
(略)我们可以使用208上的db_test_account这个数据库中的表message来测试我们的Hibernate配置是否成功。数据库样例:

建表语句:

CREATE TABLE `message` (              
`Id` varchar(50) NOT NULL default '0',
`text` varchar(50) default NULL,
`nextMessage` int(4) default NULL,
PRIMARY KEY (`Id`)
) TYPE=MyISAM

创建O/R Mapping:

点击Edit

点击New添加MySQL的驱动,保存

激活Database Explorer,保存。

选择Database Explorer,创建数据库链接:

点击创建新的数据库,添加所需必要的参数

保存,然后右键点击该数据库选择open database,测试是否配置成功,如果不能连接查看该连接的配置参数。

点击完成后MyEclipse会自动生成POJO和Map文件,并更新Hibernate的配置文件(主要是加载Map 文件)。ID Generator选项可以根据你的需要进行选择,具体含义请参阅hibernate官方文档。下面建立一个测试用的jsp页面来看看Hibernate 是否好用。
//MyJsp.jsp

<%@ page language="java" import="com.db.*" 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 'MyJsp.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>
<%
org.hibernate.Session s = HibernateUtil.currentSession();
String hql = " from Message where text='b'";
try {
org.hibernate.Query query = s.createQuery(hql);
java.util.List msgList = query.list();
hello.Message msg = (hello.Message) msgList.get(0);
out.println(msg.getId());
out.println(msg.getText());
out.println(msg.getNextmessage());
} catch (org.hibernate.HibernateException e) {
e.printStackTrace();
}
HibernateUtil.closeSession();
%>
</body>
</html>

正常的结果如下:

原帖出处

http://dev2dev.bea.com.cn/bbs/thread.jspa?forumID=121&threadID=27383&messageID=162564#162564