以Android端为客户端,servlet端为服务端的实时通讯——登录注册

接着上一篇基础Android客户端服务端交互,这次按计划实现登录注册功能,下一篇就要实现加好友的功能了
本篇源码链接:
http://download.csdn.net/detail/gywuhengy/9873558
上图片(实现功能代码里面写了,注释也很详细)
这里写图片描述

服务端接受打印log:

这里写图片描述

Android 返回打印的 log:

这里写图片描述

由图不难发现 真正的交互已经搭起来了,只需稍加判断即可

下面说说 实现过程

Android端与上一篇 相同 就省略了主要说说 服务端

1、首先建立数据库(小编这里用的是oracle数据库),建表里面有 id,username,pwd,friend,四列,将servlet连接数据库操作如下

public class GetetConnection {

    // 建立数据库连接
    public static Connection getConnection() {
        Connection conn = null;
        // 读取配置文件
        String driver = ConfigManager.getInstance().getString(
                "driver");
        String url = ConfigManager.getInstance().getString(
                "url");
        String username = ConfigManager.getInstance().getString(
                "username");
        String password = ConfigManager.getInstance().getString(
                "password");
        // 注册驱动
        try {
            Class.forName(driver);
            // 与数据库建立连接
            try {
                conn = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                System.out.println("SQLException异常");
                e.printStackTrace();
                return conn;
            }
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException异常");
            e.printStackTrace();
            return conn;
        }
        return conn;
    }
}

2、读取数据库账户信息

//读取配置文件(属性文件)的工具类
public class ConfigManager {
    private static ConfigManager configManager;
    // 读取属性文件
    private static Properties properties;

    private ConfigManager() {
        String configManager = "database.prperties";
        properties = new Properties();
        InputStream in = ConfigManager.class.getClassLoader()
                .getResourceAsStream(configManager);
        try {
            properties.load(in);
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static ConfigManager getInstance() {
        if (configManager == null) {
            configManager = new ConfigManager();
        }
        return configManager;
    }

    public String getString(String key) {

        return properties.getProperty(key);

    }


}

3、注册servlet

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    public LoginServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    /**
     * 处理get请求 request用于获得客户端信息 response用于向客户端返回信息
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 可以将逻辑放在doPost里面
        this.doPost(request, response);
    }

    /**
     * 逻辑处理
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //逻辑处理接收数据
        accentData(request,response);
    }

    // 数据接收操作
    private void accentData(HttpServletRequest request ,HttpServletResponse response) {
        // 获取客户端数据
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            String result = "";
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            System.out.println("接受数据是" + result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            String user = jsonObject.get("user").toString();
            String pwd = jsonObject.get("pwd").toString();
            System.out.println("解析后的账号" + user + "密码" + pwd);
            // 查询数据库进行
            if(user == null && pwd == null){
                System.out.println("接受值是空");
                return;
            }
            DBHandler(user,pwd,response);
        } catch (IOException e) {
            System.out.println("异常是+IOException");
            e.printStackTrace();
        }

    }


    // 数据库操作
    private void DBHandler(String user,String pwd,HttpServletResponse response ) {
        // 链接数据库 获取数据
        Connection conn = GetetConnection.getConnection();
        System.out.println("开始连接数据库");
        // 判断是否连接数据库成功
        if (conn != null) {
            System.out.println("连接数据库成功");
            // 获得Statement对象,执行SQL语句
            Statement stmt = null;
            ResultSet rs = null;
            try {
                // 查询语句
                String sql = "select PWD from CHATUSER where USERNAME='"
                        + user + "'";
                System.out.println("查询语句是" + sql);
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                if (rs.next()) {
                    // 用户存在
                    String password = rs.getString(1);
                    if (password.equals(pwd)) {
                        //返回登录成功
                         sendData(response,"success");
                    } else {
                        // 密码错误 提示
                        sendData(response,"errorpwd");
                    }

                } else {
                    // 用户不存在 提示
                    sendData(response,"errornull");
                }

            } catch (SQLException e) {
                System.out.println("SQLException异常");
                e.printStackTrace();
            } finally {
                // 释放资源
                try {
                    if (rs != null) {
                        rs.close();// 倒序释放
                    }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    System.out.println("SQLException异常");
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("连接数据库失败");
        }
    }


    // 数据返回操作
        private void sendData(HttpServletResponse response,String back) {
            try {
                PrintWriter out = response.getWriter();
                Map params = new HashMap();
                params.put("status", back);
                JSONObject jsonObject = JSONObject.fromObject(params);
                out.write(jsonObject.toString());
                out.flush();
                out.close();
            } catch (Exception e) {
                System.out.println("异常是+Exception");
            }
        }

    public void init() throws ServletException {
        // Put your code here
    }

}

4、登录servlet

public class RegisterServlet extends HttpServlet {

    public RegisterServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    /**
     * 处理get请求 request用于获得客户端信息 response用于向客户端返回信息
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 可以将逻辑放在doPost里面
        this.doPost(request, response);
    }

    /**
     * 逻辑处理
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //逻辑处理接收数据
        accentData(request,response);


    }

    // 数据接收操作
    private void accentData(HttpServletRequest request ,HttpServletResponse response) {
        // 获取客户端数据
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            String result = "";
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            System.out.println("接受数据是" + result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            String user = jsonObject.get("user").toString();
            String pwd = jsonObject.get("pwd").toString();
            System.out.println("解析后的账号" + user + "密码" + pwd);
            // 查询数据库进行
            if(user == null && pwd == null){
                System.out.println("接受值是空");
                return;
            }
            DBHandler(user,pwd,response);
        } catch (IOException e) {
            System.out.println("异常是+IOException");
            e.printStackTrace();
        }

    }


    // 数据库操作
    private void DBHandler(String user,String pwd,HttpServletResponse response ) {
        // 链接数据库 获取数据
        Connection conn = GetetConnection.getConnection();
        System.out.println("开始连接数据库");
        // 判断是否连接数据库成功
        if (conn != null) {
            System.out.println("连接数据库成功");
            // 获得Statement对象,执行SQL语句
            Statement stmt = null;
            ResultSet rs = null;
            try {
                // 查询语句
                String sql = "select PWD from CHATUSER where USERNAME='"
                        + user + "'";
                System.out.println("查询语句是" + sql);
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                if (rs.next()) {
                    // 用户存在,不能重复注册
                    sendData(response,"repeat");
                } else {
                    //用户不存在,进行注册操作
                    //注册
                    String sql1 = "INSERT INTO CHATUSER (USERNAME,PWD) " +
                            "VALUES ('"+user+"','"+pwd+"')";
                    System.out.println("插入语句是" + sql1);
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(sql1);
                    sendData(response,"success");
                }

            } catch (SQLException e) {
                System.out.println("SQLException异常");
                e.printStackTrace();
            } finally {
                // 释放资源
                try {
                    if (rs != null) {
                        rs.close();// 倒序释放
                    }
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    System.out.println("SQLException异常");
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("连接数据库失败");
        }
    }


    // 数据返回操作
        private void sendData(HttpServletResponse response,String back) {
            try {
                PrintWriter out = response.getWriter();
                Map params = new HashMap();
                params.put("status", back);
                JSONObject jsonObject = JSONObject.fromObject(params);
                out.write(jsonObject.toString());
                out.flush();
                out.close();
            } catch (Exception e) {
                System.out.println("异常是+Exception");
            }
        }

    public void init() throws ServletException {
        // Put your code here
    }

}

以上就是实现功能的主要代码,有过对小编所写感兴趣,可以继续关注小编,下一篇 将给大家带来加好友的功能,敬请期待,,,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值