1、下载dwr依赖的jar包dwr.jar
2、新建一个web工程,名称为dream,将jar包拷到lib下
3、配置web.xml,如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 配置dwr处理器 -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
4、编写Java类如下:
package com.main;
public class Check {
public boolean check(String name,String password){
if(name.endsWith("123") && password.endsWith("123"))
return true;
else
return false;
}
}
5、编写dwr.xml,在其中配置Java类,如下:
<?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="Check"><!--此javascrit配置后,dwr就自动生成Check.js,在页面js中就可以直接使用Check来调用Check类中的方法 -->
<param name="class" value="com.main.Check"></param>
</create>
<create creator="new" javascript="Hello">
<param name="class" value="com.main.Hello"></param>
</create>
</allow>
</dwr>
6、编写jsp文件,如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DWR示例</title>
<!-- 加载dwr依赖的js文件 -->
<script type="text/javascript" src="/dream/dwr/engine.js"></script>
<script type="text/javascript" src="/dream/dwr/util.js"></script>
<!-- 加载结束 -->
<!-- 加载在dwr中配置的javascript属性,由dwr自动生成的js文件 -->
<script type="text/javascript" src="/dream/dwr/interface/Check.js"></script>
<script type="text/javascript">
function login(){
var name = dwr.util.getValue("name");
var password = dwr.util.getValue("password");
Check.check(name,password,function (ok){//其中ok是Check类中的check(String name,String password)的返回值
if(ok==true){
document.getElementById("loginDiv").style.visibility = "hidden";
document.getElementById("resultDiv").style.visibility = "visible";
document.getElementById("resultDiv").innerHTML = "<font color=red size=8>欢迎你,登陆成功!</font>";
}else{
document.getElementById("resultDiv").style.visibility = "visible";
document.getElementById("resultDiv").innerHTML = "<font color=red size=8>用户名或密码错误!</font>";
}
});
}
</script>
</head>
<body>
<div id="resultDiv" style="border-color: green;border-width: 1px;border-style: outset;width: 50%;visibility: hidden;">
</div>
<div id="loginDiv" style="visibility: visible;">
姓名:<input type="text" name="name" id="name">
<br><br>
密码:<input type="password" name="password" id="password">
<br><br>
<input type="button" value="提交" onclick="login()">
</div>
</body>
</html>
dwr实例
最新推荐文章于 2020-05-08 13:38:14 发布