首先咱們搞清楚什麼叫dwr,說白了就是javascript遠程調用java代碼.搞清楚了這個直接上代碼,搞一個小例子跑一跑.javascript
第一步: 導入jar包,這個就很少說了;html
第二步:配置web.xml,java
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>TestDWR</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <listener> <listener-class> org.directwebremoting.servlet.DwrServlet</listener-class> </listener> <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> </web-app>
第三步:配置dwr.xmlweb
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://directwebremoting.org/schema/dwr30.dtd"> <dwr> <!-- 該文件放在web-inf下面 --> <allow> <create creator="new" > <!-- java類公佈成了一個js對象 --> <param name="class" value="com.gl.dwr.MyDwr" /> </create> </allow> </dwr>
第四步:jsp頁面引用本身定義的js,實現簡單效果展現app
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script> <!-- 若是要共享的js是本身定義的要加interface --> <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/MyDwr.js"></script> <script type="text/javascript"> <!--js類名調用java方法--> MyDwr.hello("world",function(data){ alert(data) }); </script> </head> <body> </body> </html>