JBuilder+Hibernate+Tomcat快速入门
高科华
作者简介:高科华,南京航空学院计算数学专业硕士,有十年以上的企业信息化工作经验。目前的研究兴趣,J2EE企业应用、ERP软件研发、数据仓库系统研发。
本文给出了用JBuilder开发Hibernate+Tomcat Web应用的一般步骤。
1. 下载hibernate-2.1.x.zip
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc
2. 安装,将zip文件解压到JBuilder_HOME\ thirdparty
3. 在JBuilder2005中新建hibernate库,选择菜单Tools-Configure-Libraries,在弹出的对话框中点击New按钮,输入hibernate库的名称:hibernate,点击Add按钮,将hibernate目录中的文件hibernate2.jar增加到hibernate库中,根据需要将hibernate\lib目录中的相应的*.jar增加到hibernate库中,一般需要这些类库:dom4j、CGLIB、Commons Collections、Commons Logging、ODMG4、EHCache
4. 新建工程文件,选菜单File-New Project,给工程文件取名为myProject
设置工程文件的属性,选菜单Project-Project Properties,选择Tomcat作为服务器,将hibernate库加入Path/Required Libraries。
5. 新建Web模块,选菜单File-New,给Web模块取名为quickstart
6. 用servlet向导新建一个servlet文件,选菜单File-New,在弹出的对话框中选择Web-Standard Servlet,取名为Servlet1,在向导的第五步选择Create a runtime configuration
7. 运行Servlet1
8. 将quickstart\Tomcat\conf目录中的文件server8080.xml加入工程文件,修改server8080.xml的内容
<?xml version="1.0" encoding="UTF-8"?>
<Server debug="0" port="8081" shutdown="SHUTDOWN">
<Service name="Catalina">
<Connector acceptCount="10" connectionTimeout="60000" debug="0" maxThreads="75" minSpareThreads="5" port="8080"/>
<Engine debug="0" defaultHost="localhost" name="Catalina">
<Host appBase="C:\jbproject\quickstart\Tomcat\webapps" autoDeploy="false" debug="0" deployXML="false" name="localhost" unpackWARs="false">
<!--Context debug="0" docBase="C:\jbproject\quickstart\quickstart" path="/quickstart" reloadable="true" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart"/-->
<Context path="/quickstart" docBase="C:\jbproject\quickstart\quickstart" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart">
<Resource name="jdbc/quickstart" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/quickstart">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- DBCP database connection settings -->
<parameter>
<name>url</name>
<value>jdbc:hsqldb:hsql://localhost</value>
<!--value>jdbc:microsoft:sqlserver://nt04:1433;DatabaseName=test</value-->
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.hsqldb.jdbcDriver</value>
<!--value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value-->
</parameter>
<parameter>
<name>username</name>
<value>sa</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<!-- DBCP connection pooling options -->
<parameter>
<name>maxWait</name>
<value>3000</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>100</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
</Server>
9. 设置hibernate,在quickstart\src目录中新建文件hibernate.cfg.xml如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/quickstart</property>
<property name="show_sql">false</property>
<property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>
<!-- Mapping files -->
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
10. 新建一个持久类
package net.sf.hibernate.examples.quickstart;
public class Cat {
private String id;
private String name;
private char sex;
private float weight;
public Cat() {
}
public String getId() {
return id;
}
private void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
11. 在quickstart\src目录中新建影射文件cat.hbm.xml如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
<!-- A 32 hex character is our surrogate key. It's automatically
generated by Hibernate with the UUID pattern. -->
<id name="id" type="string" unsaved-value="null" >
<column name="CAT_ID" sql-type="char(32)" not-null="true"/>
<generator class="uuid.hex"/>
</id>
<!-- A cat has to have a name, but it shouldn' be too long. -->
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>
<property name="sex"/>
<property name="weight"/>
</class>
</hibernate-mapping>
12. 准备数据库
13. 新建一个类HibernateUtil
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
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() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
14. 修改Servlet1.java
package net.sf.hibernate.examples.quickstart;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Query;
public class Servlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=Big5";
private HibernateUtil hibernateUtil = null;
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
hibernateUtil = new HibernateUtil();
try {
Session session = hibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Cat princess = new Cat();
princess.setName("Princess");
princess.setSex('F');
princess.setWeight(7.4f);
session.save(princess);
tx.commit();
Query query = session.createQuery(
"select c from Cat as c where c.sex = :sex");
query.setCharacter("sex", 'F');
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
for (Iterator it = query.iterate(); it.hasNext(); ) {
Cat cat = (Cat) it.next();
out.println("<p>Female Cat: " + cat.getName()+"</p>");
}
out.println("</body>");
out.println("</html>");
out.close();
tx.commit();
HibernateUtil.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Process the HTTP Put request
public void doPut(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
//Clean up resources
public void destroy() {
}
}
15. 再次运行Servlet1,报错。
16. 设置工程文件的属性,选菜单Project-Project Properties,在弹出的对话框中选择Build-Resource-xml,选择选择按钮Copy。这一步是为了在重建工程文件时把src目录中的xml文件拷贝到classes目录中。
17. 再次运行Servlet1,你将看到使用了hibernate后的显示结果。
“hibernate.cfg.xml not found”。
用JUnit测试时,文件hibernate.cfg.xml中需增加如下内容:
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="username">sa</property>
<property name="password"></property>
<property name="connection.provider_class"> net.sf.hibernate.connection.DBCPConnectionProvider</property>
<property name="connection.pool_size">50</property>
<property name="dbcp.maxActive">100</property>
<property name="dbcp.whenExhaustedAction">1</property>
<property name="dbcp.maxWait">120000</property>
<property name="dbcp.maxIdle">10</property>
高科华
作者简介:高科华,南京航空学院计算数学专业硕士,有十年以上的企业信息化工作经验。目前的研究兴趣,J2EE企业应用、ERP软件研发、数据仓库系统研发。
本文给出了用JBuilder开发Hibernate+Tomcat Web应用的一般步骤。
1. 下载hibernate-2.1.x.zip
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc
2. 安装,将zip文件解压到JBuilder_HOME\ thirdparty
3. 在JBuilder2005中新建hibernate库,选择菜单Tools-Configure-Libraries,在弹出的对话框中点击New按钮,输入hibernate库的名称:hibernate,点击Add按钮,将hibernate目录中的文件hibernate2.jar增加到hibernate库中,根据需要将hibernate\lib目录中的相应的*.jar增加到hibernate库中,一般需要这些类库:dom4j、CGLIB、Commons Collections、Commons Logging、ODMG4、EHCache
4. 新建工程文件,选菜单File-New Project,给工程文件取名为myProject
设置工程文件的属性,选菜单Project-Project Properties,选择Tomcat作为服务器,将hibernate库加入Path/Required Libraries。
5. 新建Web模块,选菜单File-New,给Web模块取名为quickstart
6. 用servlet向导新建一个servlet文件,选菜单File-New,在弹出的对话框中选择Web-Standard Servlet,取名为Servlet1,在向导的第五步选择Create a runtime configuration
7. 运行Servlet1
8. 将quickstart\Tomcat\conf目录中的文件server8080.xml加入工程文件,修改server8080.xml的内容
<?xml version="1.0" encoding="UTF-8"?>
<Server debug="0" port="8081" shutdown="SHUTDOWN">
<Service name="Catalina">
<Connector acceptCount="10" connectionTimeout="60000" debug="0" maxThreads="75" minSpareThreads="5" port="8080"/>
<Engine debug="0" defaultHost="localhost" name="Catalina">
<Host appBase="C:\jbproject\quickstart\Tomcat\webapps" autoDeploy="false" debug="0" deployXML="false" name="localhost" unpackWARs="false">
<!--Context debug="0" docBase="C:\jbproject\quickstart\quickstart" path="/quickstart" reloadable="true" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart"/-->
<Context path="/quickstart" docBase="C:\jbproject\quickstart\quickstart" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart">
<Resource name="jdbc/quickstart" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/quickstart">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- DBCP database connection settings -->
<parameter>
<name>url</name>
<value>jdbc:hsqldb:hsql://localhost</value>
<!--value>jdbc:microsoft:sqlserver://nt04:1433;DatabaseName=test</value-->
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.hsqldb.jdbcDriver</value>
<!--value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value-->
</parameter>
<parameter>
<name>username</name>
<value>sa</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<!-- DBCP connection pooling options -->
<parameter>
<name>maxWait</name>
<value>3000</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>100</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
</Server>
9. 设置hibernate,在quickstart\src目录中新建文件hibernate.cfg.xml如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/quickstart</property>
<property name="show_sql">false</property>
<property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>
<!-- Mapping files -->
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
10. 新建一个持久类
package net.sf.hibernate.examples.quickstart;
public class Cat {
private String id;
private String name;
private char sex;
private float weight;
public Cat() {
}
public String getId() {
return id;
}
private void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
11. 在quickstart\src目录中新建影射文件cat.hbm.xml如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
<!-- A 32 hex character is our surrogate key. It's automatically
generated by Hibernate with the UUID pattern. -->
<id name="id" type="string" unsaved-value="null" >
<column name="CAT_ID" sql-type="char(32)" not-null="true"/>
<generator class="uuid.hex"/>
</id>
<!-- A cat has to have a name, but it shouldn' be too long. -->
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>
<property name="sex"/>
<property name="weight"/>
</class>
</hibernate-mapping>
12. 准备数据库
13. 新建一个类HibernateUtil
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
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() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
14. 修改Servlet1.java
package net.sf.hibernate.examples.quickstart;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Query;
public class Servlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=Big5";
private HibernateUtil hibernateUtil = null;
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
hibernateUtil = new HibernateUtil();
try {
Session session = hibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Cat princess = new Cat();
princess.setName("Princess");
princess.setSex('F');
princess.setWeight(7.4f);
session.save(princess);
tx.commit();
Query query = session.createQuery(
"select c from Cat as c where c.sex = :sex");
query.setCharacter("sex", 'F');
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
for (Iterator it = query.iterate(); it.hasNext(); ) {
Cat cat = (Cat) it.next();
out.println("<p>Female Cat: " + cat.getName()+"</p>");
}
out.println("</body>");
out.println("</html>");
out.close();
tx.commit();
HibernateUtil.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Process the HTTP Put request
public void doPut(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
//Clean up resources
public void destroy() {
}
}
15. 再次运行Servlet1,报错。
16. 设置工程文件的属性,选菜单Project-Project Properties,在弹出的对话框中选择Build-Resource-xml,选择选择按钮Copy。这一步是为了在重建工程文件时把src目录中的xml文件拷贝到classes目录中。
17. 再次运行Servlet1,你将看到使用了hibernate后的显示结果。
“hibernate.cfg.xml not found”。
用JUnit测试时,文件hibernate.cfg.xml中需增加如下内容:
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="username">sa</property>
<property name="password"></property>
<property name="connection.provider_class"> net.sf.hibernate.connection.DBCPConnectionProvider</property>
<property name="connection.pool_size">50</property>
<property name="dbcp.maxActive">100</property>
<property name="dbcp.whenExhaustedAction">1</property>
<property name="dbcp.maxWait">120000</property>
<property name="dbcp.maxIdle">10</property>
相关推荐
以上就是JSP快速入门教程的主要内容,包括JSP与Java的关系、JSP涉及的技术、运行环境、开发环境、Tomcat目录结构、简单的JSP实例、JSP的运行原理以及HTML表格的语法。这些基础知识构成了JSP学习的基石,为进一步深入...
### JSP快速入门教程知识点详解 #### 一、JSP与Java的关系及JavaEE框架 JSP(Java Server Pages)是Java平台的一部分,主要用于构建动态网页。它属于JavaEE(Java Platform, Enterprise Edition)框架的一个组件,...
【JSP快速入门教程】 Java Server Pages (JSP) 是Java EE平台的一部分,它允许开发者创建动态网页。JSP和Java SE(标准版)不同,它属于Java EE(企业版),用于构建大型的企业级Web应用。Java EE包含了Web层组件...
### JSP 快速入门教程知识点详解 #### 一、JSP与Java Web的关系 - **JSP**(Java Server Pages)是Java EE标准的一部分,主要用于构建动态网页。 - JavaEE是一个广泛的标准,包含了多种技术和规范,其中包括了: ...
从开发工具Eclipse + MyEclipse和Jbuilder,到服务器端的框架Struts、Hibernate、Spring的持续升温,再加上相关的服务器软件Tomcat、Weblogic等,Java已经发展成为一个完整的产品系列。《用案例学JavaWeb整合开发:...
同时,Java EE 包括标准和流行两个体系,其中标准体系以 JSP 和 Servlet 为基础,而流行体系则常见于 Struts、Hibernate 和 Spring 这样的框架。 学习 JSP,你需要掌握以下几个核心概念: 1. **JSP 语法基础**:...
JavaWeb入门详细开发教程的知识点涵盖了从JavaWeb的基本概念到应用开发的各个方面,为初学者提供了一个全面的学习路径。以下是对该部分内容的知识点解析: 1. JavaWeb与Java平台的关系: JavaWeb是Java平台的一部分...
- **Linux+Apache+Tomcat/Jboss安装配置**:这展示了如何在Linux环境下搭建Web服务器和应用服务器的组合,Apache作为反向代理,Tomcat或JBoss作为Servlet容器。 - **Jbuilder开发环境配置**:Jbuilder是一款早期的...
### JSP 入门教程详解 #### 一、JSP 和 Java 的关系 JSP (Java Server Pages) 是一种基于 Java 的技术,用于创建动态网页。它与 Java 的关系非常紧密,具体来说: 1. **Java 标准版**:通常指的是 Java SE ...
Tomcat作为入门级Web服务器,是学习Web服务的首选。而对于应用服务器,JBoss、WebLogic和WebSphere是主流选择,其中JBoss因其开源性质和较低的成本,在实际项目中被广泛采用,适合初学者深入研究。 #### 掌握J2EE ...
1. **Dreamweaver MX**:这是一个流行的网页设计工具,可以帮助初学者快速入门HTML页面设计。 2. **HTML**:HTML是构建网页的基础语言,理解HTML标签及其用法对于任何Web开发者来说都是必不可少的。 3. **CSS**:CSS...
简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级、中级、高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情、执着,对IT的憧憬、向往!...