ajax框架DWR简单例子

什么是DWR?
   DWR是一个Open Source的 java项目。DWR可以让JavaScript调用运行在Web服务器里面的JAVA程序。简单一点或者专业一点就是Easy AJAX for JAVA.

 
1、到 http://getahead.ltd.uk/dwr/download下载dwr.jar文件。

2、用eclipse新建一个项目,我的项目名就叫dwr。

3、把刚才下载的dwr.jar放到web-inf/lib下面。

4、在web.xml中加入一下内容:
<servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.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>

5、在web.xml的所在目录下新建dwr.xml,内容如下:

<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
    "http://www.getahead.ltd.uk/dwr/dwr10.dtd">
<dwr>
  <allow>
    <create creator="new" javascript="Demo">
      <param name="class" value="com.dwrtest.java.GetDate"/>
    </create>
  </allow>
</dwr>

</dwr>

6、创建服务器端的程序com.dwrtest.java,代码如下:

package com.dwrtest.java;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GetDate {

    public String getToday() {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("EEEE-MMMM-dd-yyyy");
        Date date = new Date();
        return bartDateFormat.format(date);
    }

    public String getYesterday() {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("EEEE-MMMM-dd-yyyy");
        Date date = new Date();
        return bartDateFormat.format(new Date(date.getTime() - 86400000));
    }
}

 

7、在web目录下创建前台页面dwr.html,内容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <script src='dwr/interface/Demo.js'></script>
  <script src='dwr/engine.js'></script>
  <script language="javascript">
    function gettoday() {
      Demo.getToday(setMytext);
    }
    function getYesterday() {
      Demo.getYesterday(setMytext);
    }
    function setMytext(str) {
      document.getElementById('mytext').value = str;
    }
  </script>
    <title></title>
  </head>
  <body>
    <input type="button" value="getToday" onclick="gettoday();"/>
    <input type="button" value="getYesterday" onclick="getYesterday();"/>
    <input type="text" value="" name="mytext" id="mytext"/>
  </body>
</html>

你可能感兴趣的:(java,框架,Ajax,servlet,DWR)