DWR+Spring+Hibernate的整合

作者: jonsion  來源: javaEye  發布時間: 2010-09-26 17:20  閱讀: 2855 次  推薦: 0   原文鏈接   [收藏]  

  這兩天一直在看DWR,在做整合的時候出現了一些問題,困擾了我很久!我上網查了很多資料,但是收獲不多,今天在別人的指導下搞定了,所以把我做的發出來大家共享,以后遇到了就很好做了。主要是搞清楚各個配置文件怎么寫,特別是dwr.xml中的那些參數,我知道的都寫上了,如果不完整大家可以留言。

  先說一下我這個demo的流程。在頁面輸入一個數據庫表里的名字,然后在頁面上顯示與這個名字對應的數據庫表中的年齡。下面的代碼中我沒有寫dao層的代碼,很簡單大家自己寫吧。

  1.下面是web.xml配置文件中的部分代碼:

 
<!--配置Spring-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--配置DWR -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>

<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>

  該配置指定了DWR中的一個服務Servlet,開啟debug模式,debug模式下URL在上下文后面加上/dwr/就可以訪問DWR自動生成debug頁面。

 
</servlet>
<servlet-mapping>
 <servlet-name>dwr-invoker</servlet-name>
 <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

  2.下面就要配置dwr.xml,新建一個xml文件,寫入下面的代碼

 
<dwr>
<allow>
<create javascript="DWRUser" creator="spring">
<param name="beanName"value="DWRUser"/>
</create>
</allow>
</dwr>

 

  creator屬性的值可以是new,struts,spring......因為此處是整合spring來做的,所以設置成“spring”,javascript="DWRUser"表示實例轉換成javascript語言后以DWRUser命名,前臺頁面可以通過代碼(<script type='text/javascript' src='../../dwr/interface/DWRUser.js'></script>)來調用。param元素的name屬性值可以是class,beanName等,此處用beanName,value得值是定義在applicationContext.xml中某個bean的id值。

  3.接下來是Spring的配置文件。下面是我用到的兩個bean 的代碼,其它的數據庫鏈接和Hibernate配置就自己完成吧

 
<bean id="dao" class="wj.dao.HelloWorld">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="DWRUser" class="wj.service.HelloWorldSevice">
<property name="hello">
<ref bean="dao"/>
</property>
</bean>

  4. 然后就是Service層的代碼,這里的方法就是在頁面中要調用的

 

 
package wj.service;
import wj.dao.HelloWorld;
public class HelloWorldSevice {
//dao層注入 
private HelloWorld hello;
public HelloWorld getHello(){
return hello;
}

public void setHello(HelloWorld hello){
this.hello = hello;
}

public String HelloService(String name){
return hello.sayHello(name);//調用dao層的方法
}
}

 

  5. 頁面代碼

  在頁面中首先寫入以下代碼,這些代碼在DWR自動生成的debug頁面中可以得到

 

 
<script type='text/javascript' src='/DWRSecond/dwr/interface/DWRUser.js'></script>
<script type='text/javascript' src='/DWRSecond/dwr/engine.js'></script>
<script type='text/javascript' src='/DWRSecond/dwr/util.js'></script>

以下是具體的調用

 

 

 
<script type="text/javascript">
function first()
{
DWRUser.HelloService($(
"name").value,callback);
}

function callback(data)
{
document.getElementById(
"msg1").innerHTML = data;
}

</script>

 

 

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()