步骤:
导入 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
packagecom; publicclassDwrHello{ publicStringhello(Stringworld){ System.out.println("hello"+world); return"hello"+world; } }
4. web-inf 下新建一个 dwr.xml,如下:
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEdwrPUBLIC "-//GetAheadLimited//DTDDirectWebRemoting2.0//EN" "http://getahead.org/dwr/dwr20.dtd"> <dwr> <allow> <createcreator="new"javascript="DwrHello"> <paramname="class"value="com.DwrHello"/> </create> </allow> </dwr>
5. 新建 index.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <basehref="<%=basePath%>"> <title>DWRDEMO</title> </head> <scripttype='text/javascript'src='dwr/engine.js'></script> <scripttype='text/javascript'src='dwr/util.js'></script> <scripttype="text/javascript"src="dwr/interface/DwrHello.js"></script> <scripttype="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);
原文链接:https://www.f2er.com/ajax/162475.html