dwr学习之基础篇

DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。
安装DWR时会配置一个servlet,这个servlet记得吧?他就是负责把前台的JS参数封装成JAVA,去调用你的JAVA类,然后将返回结果(JAVA类型)再翻译成JS生成到你的JSP页面上,给你的错觉就是你用JS直接调用了JAVA方法。

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
<listener>
    <listener-class>org.directwebremoting.servlet.DwrListener</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>
  
    <load-on-startup>1</load-on-startup>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>	
</web-app>

 

dwr.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd">

<dwr>

  <allow>

    <!--
    <filter class="com.example.dwr.monitor.MonitoringAjaxFilter"/>
    <filter class="org.directwebremoting.filter.ExtraLatencyAjaxFilter">
      <param name="delay" value="200"/>
    </filter>
    -->

    <create creator="new">
      <param name="class" value="com.cz.model.MyDwr"/>
    </create>

  </allow>

</dwr>

 

MyDwr.java:

package com.cz.model;

/** 
 * @ClassName: MyDwr 
 * @Description: dwr测试类
 * @author chenzheng
 * @date 2013-4-4 下午08:53:07 
 */
public class MyDwr {

	/**
	 * @author chenzheng
	 * @since 2013-4-4
	 * @Description: js调用java
	 * @throws
	 * @param world
	 * @return
	 * String
	 */
	public String hello(String world) {
		System.out.println("hello "+world);
		return "hello "+world;
	}
}

 

index.jsp:

<%@ 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>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/MyDwr.js"></script>
<script type="text/javascript">
	MyDwr.hello("世界",function(data){
		alert(data);
	});
</script>
</head>
<body>

</body>
</html>

 

你可能感兴趣的:(入门,DWR)