DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数,就像它就在浏览器里一样。

DWR不认为浏览器/WEB服务器协议是重要的,而更乐于保证编程界面的简单自然.对此最大的挑战就是把AJAX的异步特性和正常JAVA方法调用的同步特性相结合.在异步模式下,结果数据在开始调用之后的一段时间之后才可以被异步访问获取到.DWR允许WEB开发人员传递一个回调函数,来异步处理Java函数调用过程.

把你后台的代码弄到js里面,当成一个函数来调用,是不是会方便很多。用起来都说好的一个框架,记得当年我去面试的时候居然有面试官不知道这个东西还技术总监,瞬间就觉得自己高大上了。

好了程序猿要用代码说话

是准备jar包啦,这两个jar,也可以通过maven自动下依赖

这里想了想还是用maven来弄这个吧

第一步新建maven工程   结构图

 

第二步,自然是添加依赖啊

<dependency>
    <groupId>org.directwebremoting</groupId>
    <artifactId>dwr</artifactId>
    <version>2.0.3</version>
</dependency>


<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.42</version>
</dependency>

这四个就好了

新建jsp了

index.jsp

<jsp:forward page="/WEB-INF/jsp/first.jsp"></jsp:forward>

first.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>dwr test</title>
</head>
<%
String path = request.getContextPath();


%>
<script type="text/javascript" src="<%=path%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=path%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=path%>/dwr/interface/DbdoSomething.js"></script>
<script type="text/javascript">


window.onload = function(){ 
var btn = document.getElementById("sign"); 
btn.onclick = function(){ 
var msgData = document.getElementById("msg").value;
DbdoSomething.Send(msgData,function(data){
alert(data);
});
} 
}
</script>
<body>
<ul id="ul" style="color:red;font-size:60px"></ul>
<input type="text" name="msg" id="msg"/>
<input type="button" id="sign" value="查询信息"/>
</body>
</html>

然后新建dwr文件夹,里面放置从dwr-XXXX.jar里面找的这两个js

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>dwr</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
   <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>
    <init-param>
      <param-name>allowGetForSafariButMakeForgeryEasier</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>activeReverseAjaxEnabled</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>crossDomainSessionSecurity</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>allowScriptTagRemoting</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.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"  
  "http://getahead.org/dwr/dwr20.dtd">
  
<dwr>
<allow>
<create creator="new" javascript="DbdoSomething">
<param name="class">com.zkb.DbdoSomething</param>
</create> 
</allow>
</dwr>

这里头部<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"  

  "http://getahead.org/dwr/dwr20.dtd">根据你当前依赖的jar声明,不同的话会报错这里

弄完之后webapp里面的截图就是这样

java部分我就不拆出来写数据库配置文件啦,直接写代码里面,需要自己修改,一切从简

DbdoSomething.java

package com.zkb;


import java.sql.ResultSet;
import java.sql.SQLException;


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.zkb.db.DbCon;


public class DbdoSomething {

public String Send(String msg) throws SQLException{
String json ="";

DbCon db= new DbCon();
Connection conn = (Connection) db.getConnection(); 
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = (Statement) conn.createStatement();
            rs = stmt.executeQuery("select id,username,password from userinfo where username='"+msg+"'");
            
            while(rs.next()){
            json ="{\"name\":"+rs.getString("username")+",\"id\":"+rs.getString("id")+",\"pass\":"+rs.getString("password")+"}";
            }
           
        } catch (Exception e) {
            e.printStackTrace();
        } finally {   
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
                if (!stmt.isClosed()) {
                    stmt.close();
                }
                if (!rs.isClosed()) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return json;
}
}

DbCon.java

package com.zkb.db;


import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;


import javax.sql.DataSource;
public class DbCon implements DataSource {



private static String driver = "com.mysql.jdbc.Driver";
private static String dbUrl = "jdbc:mysql://localhost:3306/userdb";
    private static String dbUserName ="root";
    private static String dbPassWord ="root";
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}


@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}


@Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
// TODO Auto-generated method stub


}


@Override
public void setLoginTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub


}


@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}


@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}


@Override
public Connection getConnection() throws SQLException {
Connection con =null;
try {  
        Class.forName(driver);
             con =DriverManager.getConnection(dbUrl, dbUserName, dbPassWord);  
          } catch (Exception e) {
             e.printStackTrace();  
          }  
return con;
}
@Override
public Connection getConnection(String arg0, String arg1)
throws SQLException {
// TODO Auto-generated method stub
return null;
}


@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}


}

java部分截图

 

数据库

CREATE TABLE `userinfo` (
  `id` int(8) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;


-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES ('1', 'admin', 'admin');
INSERT INTO `userinfo` VALUES ('2', 'user', 'user');
INSERT INTO `userinfo` VALUES ('3', 'pass', 'pass');

运行截图

这就弄好了,不要介意我的命名啊,我一个demo东改西改的名字肯定会不一样,注重结果

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐