dwr 环境搭建。
L行天下
9年前
来自: http://my.oschina.net/u/1474779/blog/610635
步骤:
导入 dwr.jar 和 commons-logging-1.1.1.jar 包,因为dwr依赖与 commons-logging-1.1.1.jar
web.xml 中配置 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> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
3. 新建需要 js 调用的 java类 DwrHello.java
package com; public class DwrHello { public String hello(String world){ System.out.println("hello "+world); return "hello "+world; } }
4. web-inf 下新建一个 dwr.xml , 如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd"> <dwr> <allow> <create creator="new" javascript="DwrHello"> <param name="class" value="com.DwrHello" /> </create> </allow> </dwr>
5. 新建 index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>DWR DEMO</title> </head> <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/DwrHello.js"></script> <script type="text/javascript"> DwrHello.hello("世界",function(data){ alert(data); }); </script> <body> </body> </html>
注意:
engine.js/util.js 必须如上面所写
DwrHello.js 对应的是 DwrHello.java ,在 dwr.xml 中配置的。
DwrHello.hello("世界"); 这样即可调用 DwrHello.java 中的 hello(String world) 方法。
DwrHello.hello("世界",function(data){
alert(data);
}); 这样子采用回调函数得到 hello(String world) 方法的返回值。