dwr 前台调用后台的java类 hello

dwr 前台调用后台的java类  hello

web项目,service  tomcat

第一部:在web.xml中引入dwr类库

web.xml
<?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>dwr_test</display-name>
 
 
  <servlet>
  <display-name>DWR Servlet</display-name>
  <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>
 
 
 
  <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>
</web-app>



第二部:准备后台java类供前台调用
Demo.java

package org.getahead.dwrdemo.simpletext;

public class Demo {

public String sayHello(String name) {
return "Hello, " + name;
}
}


第三步:在WEB-INF/下加入文件dwr.xml与web.xml同级目录
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>
    <create creator="new" javascript="Demo">
      <param name="class" value="org.getahead.dwrdemo.simpletext.Demo"/>
    </create>
  </allow>
</dwr>


第四步,前台js调用

<%@ 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>
</head>

《!--引入dwr工程  必须要--》
<script src='/dwr_test/dwr/engine.js'></script>   

《!--引入dwr  工具类库,需要用时才,引入,不是必须要--》
<script type='text/javascript' src='/dwr_test/dwr/util.js'></script>

《!--dwr配的java类,dwr自动生成一个可以调用java类的js,必需要引入此类--》
<script src='/dwr_test/dwr/interface/Demo.js'></script>


<script>

function update() {
  var name = dwr.util.getValue("demoName");
  Demo.sayHello(name, function(data) {
    dwr.util.setValue("demoReply", data);
  });
}
</script>


<body>


<p>
  Name:
  <input type="text" id="demoName"/>
  <input value="Send" type="button" onclick="update()"/>
  <br/>
  Reply: <span id="demoReply"></span>
</p>
</body>
</html>













 

你可能感兴趣的:(dwr demo)