我的dwr Hello World

公司要用到dwr(dwr2点几版本的),趁着放假在家里花了点时间弄了一下,只是helloworld。基本上是按照官方网站上的流程做的,在这里记一下,方便查看:

1,当然是下载相关包:dwr.jar,commons-logging.jar,将它们加入到应用里

2,在web.xml中加入如下配置:

 

<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
   <param-name>debug</param-name>
   <param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

3,编写相关的类和方法,如:

 

package dwr;

public class HelloDWR {
	public String sayHelloToDWR(String name1,String name2) {
		return name1+" say Hello to DWR "+name2;
	}
}

 

 4,在web.xml同一目录下建立文件dwr.xml文件,给类和方法加入相关配置:

 

<dwr>
  <allow>
    <create creator="new" javascript="Hello">
      <param name="class" value="dwr.HelloDWR"/>
    </create>
    <!-- 
    <create creator="xxx" javascript="yyy">
      <param name="class" value="x.y.z"/>
    </create>
     -->
  </allow>
</dwr>

 此时,在浏览器上访问:http://localhost:8888/dwr/dwr/(根据本机情况定),可以看到已经定义了的类的信息,点几相关类进入详细信息,将以下js代码拷贝到你需要用到该类的页面:

 

 <script type='text/javascript' src='/dwr/dwr/interface/Hello.js'></script>
  <script type='text/javascript' src='/dwr/dwr/engine.js'></script>

 在页面中应用如:

 

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
	<script type='text/javascript' src='/dwr/dwr/interface/Hello.js'></script>
  	<script type='text/javascript' src='/dwr/dwr/engine.js'></script>
  </head>
  <script type="text/javascript">
  	function sayHello() {
  		var result = document.getElementById("dwrTest").value;
  		Hello.sayHelloToDWR(result,result+"2",popup);
  	} 
  	function popup(str) {
  		alert(str);
  	}
  </script>
  <body>
    <input type="text" id="dwrTest"/>
    <input type="button" onclick="javascript:sayHello();" value="lock">
  </body>
</html>

 在输入框输入内容,点击lock按钮即可以看到效果。

你可能感兴趣的:(JavaScript,Web,xml,servlet,DWR)