1.下载dwr和spring的相关jar包

2.配置web.xml

<!-- dwr框架配置(spring) -->
<servlet>
	<servlet-name>dwrServlet</servlet-name>
	<servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class>
	<init-param>  
            <param-name>debug</param-name>  
            <param-value>true</param-value>  
    </init-param> 
</servlet>

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


3.编写暴露给前台调用的类

package com.spring.action;


public class DwrClass {


	public void sayHello(){
		System.out.println("Hello Word!");
	}
	
	
	public String sayHelloWord(String username){
		return username+": HelloWord!";
	}
}


4.配置applicationContext.xml

  <!-- dwr配置 -->
    <bean id="dwrBean" class="com.spring.action.DwrClass">
    	<dwr:remote javascript="DwrFunction"> <!-- 暴露给js调用的组件名 -->
    		<dwr:include method="sayHello"/><!-- 暴露的方法 -->
    		<dwr:include method="sayHelloWord"/><!-- 暴露的方法 -->
    	</dwr:remote>
    </bean>
    
    <!-- 被用到的pojo -->
    <!-- 
	    <dwr:configuration>
	    	<dwr:convert type="采用的转换类型" class="需要转换的自定义类型全限定名"></dwr:convert>
	    </dwr:configuration>
	 -->

5.编写前台调用js

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Dwr.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="dwr/engine.js"></script>
    <script type="text/javascript" src="dwr/util.js"></script>
    <script type="text/javascript" src="dwr/interface/DwrFunction.js"></script>
    <script type="text/javascript">
    function sayHello(){
    	DwrFunction.sayHello();
    }
    
    
    function sayHelloWord(){
    	DwrFunction.sayHelloWord("cabbage-z",function(data){
    		alert(data);
    	});
    }
    </script>
  </head>
  
  <body>
    <input type="button" value="说话" οnclick="sayHelloWord();" >
  </body>
</html>
ps: 注意html中的3个js的引用.dwr/engine.js和dwr/util.js这两个是jar包自带的,dwr/interface/DwrFunction.js这个是通过配置暴露给前台的方法名所自动创建的js

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐