您的位置:首页 > 运维架构 > Tomcat

在spring+hibernate中使用tomcat5.5的jndi数据源

2007-07-13 21:16 519 查看

在spring中使用tomcat提供的JNDI 数据源

JNDI是J2EE中一个很重要的标准,通常我们是在J2EE编程中用到,Tomcat中提供了在JSP和Servelt中直接使用JNDI的方法,主要是通过dbcp连接池,下面谈一下我在Tomcat5.5中配置和使用JNDI的方法。
在eclispe中使用myeclipse建立web工程。然后按照以下步骤,完成此项目的配置流程。
1,首先需要在如下目录中建立工程所在的发布的xml文件

Web的发布路径

2,编辑如图所示的myprj.xml文件,其内容如下所示:
<Context docBase="D:/myprj/WebRoot"
privileged="true" antiResourceLocking="false" antiJARLocking="false">

Tomcat5.5.9中数据库JNDI的名字

<!-- Link to the user database we will get roles from -->
<ResourceLink name="users" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/>

驱动类型

<Resource name="jdbc/pubs"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"
username="sa"
password="123456"
maxActive="20"
maxIdle="10"
maxWait="10000"/>

</Context>

编写完成后,保存退出。
再修改在eclipse中建立的web工程的web.xml文件,其代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<resource-ref>
<res-ref-name>jdbc/pubs</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

3,在数据库的查询分析其中建立emp表
create table emp(
eid int identity primary key,
ename varchar(50),
address varchar(100)
)
4,在eclipse中使用myeclipse中先加入Hibernate组件,并使用数据库查看器建立与mssql server的连接,要求能够看到数据库的emp表。
5,添加spring组件,并加入Hibernate的sessionFactory,用spring管理Hibernate的数据库连接。这时系统会自动生成applicationContext.xml文件。
6,使用Myeclipse自带的数据库浏览视图,将emp表生成为相应得持久化类

在生成过程中,选择生成spring的dao类,生成完成后会出现如下的结构:

其中EmpDAO的代码如下:
package com.po;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
* Data access object (DAO) for domain model class Emp.
* @see com.po.Emp
* @author MyEclipse - Hibernate Tools
*/
public class EmpDAO extends HibernateDaoSupport {

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

//property constants
public static final String ENAME = "ename";
public static final String ADDRESS = "address";

protected void initDao() {
//do nothing
}

public void save(Emp transientInstance) {
log.debug("saving Emp instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}

public void delete(Emp persistentInstance) {
log.debug("deleting Emp instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public Emp findById( java.lang.Integer id) {
log.debug("getting Emp instance with id: " + id);
try {
Emp instance = (Emp) getHibernateTemplate()
.get("com.po.Emp", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}

public List findByExample(Emp instance) {
log.debug("finding Emp instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}

public List findByProperty(String propertyName, Object value) {
log.debug("finding Emp instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Emp as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}

public List findByEname(Object ename) {
return findByProperty(ENAME, ename);
}

public List findByAddress(Object address) {
return findByProperty(ADDRESS, address);
}

public Emp merge(Emp detachedInstance) {
log.debug("merging Emp instance");
try {
Emp result = (Emp) getHibernateTemplate()
.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public void attachDirty(Emp instance) {
log.debug("attaching dirty Emp instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(Emp instance) {
log.debug("attaching clean Emp instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public static EmpDAO getFromApplicationContext(ApplicationContext ctx) {
return (EmpDAO) ctx.getBean("EmpDAO");
}
}

7,添加struts组件,并建立EmpAction,用于测试最终的结果。EmpAction代码如下:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 org.springframework.context.support.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.struts.DelegatingActionProxy;
import com.po.*;
/**
* MyEclipse Struts
* Creation date: 03-05-2007
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class EmpAction extends Action {
/*
* Generated Methods
*/

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
private EmpDAO edao;

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
Emp emp=new Emp();
edao=this.getEdao();
emp.setEname("hello");
emp.setAddress("good");
edao.save(emp);

return null;
}
public EmpDAO getEdao() {
return edao;
}
public void setEdao(EmpDAO edao) {
this.edao = edao;
}

}

8,将action组件注入到spring的applicationContext.xml文件中。
9,修改struts-config.xml文件,加入applicationContext.xml的路径(使用spring的插件来完成对applicationContext.xml文件的加载),并使用spring的struts代理类来代理Action,最终struts-config.xml文件的代码如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

Spring代理struts的类

<struts-config>
<data-sources />
<form-beans />
<global-exceptions />
<global-forwards />
<action-mappings >
<action path="/emp" type="org.springframework.web.struts.DelegatingActionProxy" />

</action-mappings>

<message-resources parameter="com.struts.ApplicationResources" />
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">

加载spring的applicationContext.xml文件的插件类

<set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" />
</plug-in>
</struts-config>

10,在spring的applicationContext.xml文件中加入数据源dataSource,使用tomcat5.5.9中配置的JNDI数据源,则完整的applicationContext.xml文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>

Spring的jndi解析工厂类

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">

Tomcat5.5.9中的JNDI数据源

<value>java:comp/env/jdbc/pubs</value>
</property>
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/po/Emp.hbm.xml</value>
</list>
</property>
</bean>
<bean id="EmpDAO" class="com.po.EmpDAO">

将struts的Action注入到spring中的代码

<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>

<bean name="/emp" class="com.struts.action.EmpAction">
<property name="edao">
<ref bean="EmpDAO" />
</property>
</bean>
</beans>
配置图如下所示:

最后,启动tomcat5.5.9测试我们的工程,在ie中测试如下所示,若果没有出现错误提示,则说明测试通过,否则,按上述步骤,重新检查配置过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: