zoukankan      html  css  js  c++  java
  • DWR框架应用简单例子

    1.前言:本文主要是针对DWR框架的实际应用进行讲解,通过一个登陆信息实时验证来讲述DWR的使用过程。

    2.在Myeclipse中建立一个Web应用项目.首先在web.xml中对dwr进行配置。配置内容如下:

    <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>

    3.新建一个Java类用来验证登陆信息,主要包括用户名,密码,用户类型,这些信息在数据库中对应于数据库news中的用户信息users表,在这里我们将users表的建表代码列出如下:

    create database news

    go

    use news

    create table users

    (

            username varchar(50) default('')primary key,

            password varchar(50) default(''),

            type varchar(50)default('normal')

     Java类:

    package dwr.test;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;

    public class Validator {
     private static String username;
     private static String password;
     private static String type;
     private Connection conn;
     private PreparedStatement ps;
     private ResultSet rs;

     public void init() {
      try {
       conn = DBConnection.getConnection();
       Debug.println(conn.toString());
      } catch (Exception e) {
       Debug.println("没有获得连接!");
       e.printStackTrace();
      }
     }

     public List<String> getAllType() {
      init();
      List<String> typelist = new ArrayList<String>();
      try {
       ps = conn.prepareStatement("select distinct(type) from loginfo");
       rs = ps.executeQuery();
       while (rs.next()) {
        typelist.add((String) rs.getString("type"));
       }
      } catch (Exception e) {
       
       e.printStackTrace();
      }
      close();
      return typelist;
     }

     public String validate(int i) {
      Debug.println("num:" + i);
      init();
      String sql1 = "select * from loginfo where type=?";
      String sql2 = "select * from loginfo where type=? and username=?";
      String sql3 = "select * from loginfo where username=? and password=? and type=?";
      try {
       if (i == 1) {
        ps = conn.prepareStatement(sql1);
        ps.setString(1, type);
        rs = ps.executeQuery();
        Debug.println(sql1);
        if (!rs.next()) {
         return "此部门没有用户!";
        }
       } else if (i == 2) {
        ps = conn.prepareStatement(sql2);
        ps.setString(1, type);
        ps.setString(2, username);
        rs = ps.executeQuery();
        Debug.println(sql2);
        if (!rs.next())
         return "用户名错误!";
       } else if (i == 3) {
        ps = conn.prepareStatement(sql3);
        ps.setString(1, username);
        ps.setString(2, password);
        ps.setString(3, type);
        Debug.println(sql3);
        rs = ps.executeQuery();
        if (!rs.next())
         return "用户密码错误!";
       }
       return null;
      } catch (Exception e) {
       Debug.println("判断时出现异常!");
       e.printStackTrace();
      } finally {
       close();
      }
      return "判断时出现了异常";
     }

     public void close() {
      try {
       if (rs != null)
        rs.close();
       if (ps != null)
        ps.close();
       if (conn != null)
        conn.close();
      } catch (Exception e) {
       e.printStackTrace();
      }
     }

     public void setUsername(String username) {
      Debug.println("username:" + username);
      this.username = username;
     }

     public void setPassword(String password) {
      Debug.println("password:" + password);
      this.password = password;
     }

     public void setType(String type) {
      Debug.println("type:" + type);
      this.type = type;
     }

     public static void main(String args[]) {
      Validator v = new Validator();
      v.setUsername("jiangbin");
      v.setPassword("jiangbin");
      v.setType("管理员");
      if (v.validate(3) == null)
       Debug.println("找到了用户!");
     }
    }

    其中引用的数据库池边类为:

    package dwr.test;

    import java.sql.Connection;

    import javax.sql.DataSource;

    import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

    public class DBConnection {
     private static DataSource dataSource;

     public static Connection getConnection() throws Exception {
      if (dataSource == null) {
       BasicDataSource bds = new BasicDataSource();
       bds
         .setDriverClassName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
       bds
         .setUrl("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=news");
       bds.setUsername("sa");
       bds.setPassword("");
       bds.setMaxIdle(2);
       bds.setMaxActive(20);
       bds.setDefaultAutoCommit(true);
       dataSource = bds;
      }
      return dataSource.getConnection();
     }
    }

    其中引用的Debug类为:

    /*
     * Debug.java
     */

    /*
     *  Copyright (c) 2001 by Florian Bomers <florian@bome.com>
     *
     *
     *   This program is free software; you can redistribute it and/or modify
     *   it under the terms of the GNU Library General Public License as published
     *   by the Free Software Foundation; either version 2 of the License, or
     *   (at your option) any later version.
     *
     *   This program is distributed in the hope that it will be useful,
     *   but WITHOUT ANY WARRANTY; without even the implied warranty of
     *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *   GNU Library General Public License for more details.
     *
     *   You should have received a copy of the GNU Library General Public
     *   License along with this program; if not, write to the Free Software
     *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
     *
     */

    package dwr.test;

    public class Debug {

     public static boolean ERROR = true;
     public static boolean DEBUG = true;
     public static boolean TRACE = true;
     public static boolean TRACE_READWRITE = true;
     public static boolean TRACE_INOUT = false;
     public static boolean SHOW_ALL_EXCEPTIONS = true;

     // for net.Server
     public static boolean SLOW_NET_UPLOAD = true;
     public static boolean SLOW_NET_DOWNLOAD = true;

     // show the time of a debug message
     private static final boolean SHOW_TIMES = true;
     private static long START_TIME = System.currentTimeMillis();

     public static synchronized void println(String sMessage) {
      if (TRACE) {
       if (SHOW_TIMES) {
        sMessage = "" + (System.currentTimeMillis() - START_TIME)
          + ": " + sMessage;
       }
       System.out.println(sMessage);
      }
     }

     public static void println(Object obj, String sMessage) {
      if (TRACE) {
       String cn = obj.getClass().getName();
       int i = cn.lastIndexOf('.');
       if (i >= 0 && i < cn.length() - 1) {
        cn = cn.substring(i + 1);
       }
       println(cn + ": " + sMessage);
      }
     }

     public static synchronized void println(Throwable t) {
      if (TRACE) {
       t.printStackTrace();
      }
     }

     public static synchronized void printStackTrace() {
      if (TRACE) {
       Thread.dumpStack();
      }
     }
    }
    4.创建dwr.xml文件将Java验证类与页面脚本对象进行关连,dwr.xml文件与web.xml文件于同级目录下:

    <?xml version="1.0" encoding="GB18030"?>
    <dwr>
      <allow>
        <create creator="new" javascript="validator">
          <param name="class" value="dwr.test.Validator"/>
        </create>
      </allow>
    </dwr>

    5.建立登录页面index.jsp,其页面代码如下:

    <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
    <html>
     <head>
      <title>Log page</title>
      <script type='text/javascript' src='./dwr/interface/validator.js'></script>
      <script type='text/javascript' src='./dwr/engine.js'></script>
      <script type='text/javascript' src='./dwr/util.js'></script>
      <script type="text/javascript" src="./js/log.js"></script>
     </head>

     <body onload="addUserType();">
      <font color="red" size="4"><div id="isUser"></div>
      </font>
      <hr>
      <form action="success.jsp">
       <TABLE>
        <TR>
         <TD colspan="3" bgcolor="#6699FF">
          登录
         </TD>
        </TR>
        <TR>
         <TD>
          用户类型
         </TD>
         <TD>
          <select id="type" onblur="reply('1');">
          </select>
         </TD>
         <TD>
          <div id='typeText'></div>
         </TD>
        </TR>
        <TR>
         <TD>
          用户名
         </TD>
         <TD>
          <input type="text" name="username" onblur="reply('2');" />
         </TD>
         <TD>
          <div id='usernameText'></div>
         </TD>
        </TR>
        <TR>
         <TD>
          密码
         </TD>
         <TD>
          <input type="password" name="password" onblur="reply('3');" />
         </TD>
         <TD>
          <div id='passwordText'></div>
         </TD>
        </TR>
        <TR>
         <TD colspan="3">
          <input type="button" value="提交" onclick="check();" />
          <input type="reset" value="重置" />
         </TD>
        </TR>
       </TABLE>
      </form>
     </body>
    </html>
    6.页面中引用的log.js文件如下:


    function callback1(str) {
     DWRUtil.setValue("isUser", str);
    }
    function callback2(str) {
     DWRUtil.setValue("isUser", str);
    }
    function callback3(str) {
     DWRUtil.setValue("isUser", str);
    }
    function callback4(str) {
     if (str == null) {
      location.href = "success.jsp";
     } else {
      DWRUtil.setValue("isUser", "\错\误\:\您\输\入\的\用\户\信\息\不\存\在!");
     }
    }
    function reply(num) {
     var type = DWRUtil.getValue("type");
     if (type == "\请\选\择") {
      DWRUtil.setValue("isUser", "\请\选\择\用\户\类\型!");
      return;
     }
     var username = DWRUtil.getValue("username");
     var password = DWRUtil.getValue("password");
     validator.setType(type);
     validator.setUsername(username);
     validator.setPassword(password);
     if (num == "1") {
      validator.validate(1, callback1);
     }
     if (num == "2") {
      validator.validate(2, callback2);
     }
     if (num == "3") {
      validator.validate(3, callback3);
     }
     if (num == "4") {
      validator.validate(3, callback4);
     }
    }
    function addUserType() {
     validator.getAllType(allType);
    }
    function allType(typeList) {
     var obj_Type = document.getElementById("type");
     DWRUtil.removeAllOptions(obj_Type);
     DWRUtil.addOptions(obj_Type, ["\请\选\择"]);
     DWRUtil.addOptions(obj_Type, typeList);
    }
    function check() {
     reply(4);
    }

    将项目布署到tomcat上就可以了,注意在构建路径上引用dwr,jar包。

  • 相关阅读:
    C#获取上级文件夹路径
    C#string与byte数组转行
    C#BAT与VBS文件的创建和执行调用
    C#生成条形码
    C#根据生日计算所属十二星座
    C#获取某一字符串第N到第N+1空格的字符
    WPF的DataGrid表格动态加载合并列
    WPF递归设置CheckBox与TextBox禁用联动
    WPF基础知识
    WPF Popup绑定目标控件上下左右位置
  • 原文地址:https://www.cnblogs.com/elleniou/p/3016225.html
Copyright © 2011-2022 走看看