如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?


这篇博客主要介绍的是如何编写Android登录注册服务端代码,通过servlet和jdbc方式分别对客户端传输的数据和数据库进行处理操作。

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。Servlet 的主要功能在于交互式地浏览和修改数据,生成动态 Web 内容。这个过程为:
1、客户端发送请求至服务器端;
2、服务器将请求信息发送至 Servlet;
3、Servlet 生成响应内容并将其传给服务器。响应内容动态生成,通常取决于客户端的请求;
4、服务器将响应返回给客户端。

1、下载安装Tomcat服务器

2、打开eclipse,选择Java EE模式

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第1张图片

3、配置Servers

①点击底部配置框中的蓝色字

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第2张图片

②在server type中选择Apache和Tomcat相应的版本

③添加Server runtime environment

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第3张图片

④选择下载解压好的Tomcat路径

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第4张图片

⑤配置Server Locations

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第5张图片

4、新建一个动态web工程,并勾选Generate web.xml deployment descriptor选项。

如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第6张图片
如何使用Jdbc和Servlet操作Mysql数据库,编写Android登录注册服务端?_第7张图片

5、将下载好的mysql-connect-java-5.1.18-bin.jar包导入项目中(http://download.csdn.net/download/sconghw/10153718)

6、编写服务器登录类

1. JdbcHello类,从Mysql数据库中查询用户名和密码,返回一个包含查询结果的数组。

package com.scong.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import com.mysql.jdbc.Driver;

public class JdbcHello {

    private ResultSet resultSet;
    private Statement statement;
    private Connection connection;

    @Test
    public String[] loginStrings(){
    String[] nameStrings=new String[100];
    int i=0;
        //注册驱动 注册mysql驱动
        try {
            DriverManager.registerDriver(new Driver());
            //mysql服务器的地址 jdbc:子协议(mysql)://服务器ip地址:端口(默认3306)/数据库名字
            String url="jdbc:mysql://xxx.xxx.xxx.xxx:3306/login";
            //访问mysql服务端的用户名
            String username="root";
            //访问mysql服务端的密码
            String password="123456";
            connection = DriverManager.getConnection(url,username, password);
            statement = connection.createStatement();
            String sql="select * from user;";
            resultSet = statement.executeQuery(sql);
            //调用next()方法移动光标到下一行
            while(resultSet.next()){
                String name=resultSet.getString(1);
                String pwString=resultSet.getString(2);
                //System.out.println(name);
                nameStrings[i]=name+"##"+pwString;
                i++;
            }
            //return nameStrings;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{  //关闭连接
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return nameStrings;
    }

}

2. LoginTest类继承至Servlet类,可以对从客户端传输的登录数据进行处理操作。

package com.scong.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scong.db.JdbcHello;

/**
 * Servlet implementation class LoginTest
 */
@WebServlet("/LoginTest")
public class LoginTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginTest() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String usernameString = request.getParameter("username");
        String passwordString = request.getParameter("password");
        JdbcHello jdbcHello = new JdbcHello();
        String[] name = jdbcHello.loginStrings();
        PrintWriter writer = response.getWriter();
        if (usernameString == null || passwordString == null
                || usernameString.length() == 0 || passwordString.length() == 0) {
            writer.print("false!");
        } else {
            int i = 0;
            String temp = usernameString + "##" + passwordString;

            for (i = 0; i < name.length; i++) {

                if (temp.equals(name[i])) {
                    writer.print("true");                   
                    break;
                }
            }
            if (i == name.length) {
                writer.print("login false!");
            }

        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

7、编写服务端注册类

1. JDBCEqual类,从数据库中查询账号,返回一个包含所有账号的数组。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import com.mysql.jdbc.Driver;

public class JDBCEqual {

    private ResultSet resultSet;
    private Statement statement;
    private Connection connection;

    @Test
    public String[] RegisterEqual(){
    String[] nameStrings=new String[100];
    int i=0;
        //注册驱动 注册mysql驱动
        try {
            DriverManager.registerDriver(new Driver());
            //mysql服务器的地址 jdbc:子协议(mysql)://服务器ip地址:端口(默认3306)/数据库名字
            String url="jdbc:mysql://xxx.xxx.xxx.xxx:3306/login";
            //访问mysql服务端的用户名
            String username="root";
            //访问mysql服务端的密码
            String password="123456";
            connection = DriverManager.getConnection(url,username, password);
            statement = connection.createStatement();
            String sql="select * from user;";
            resultSet = statement.executeQuery(sql);
            //调用next()方法移动光标到下一行
            while(resultSet.next()){
                String name=resultSet.getString(1);
                //System.out.println(name);
                nameStrings[i]=name;
                i++;
            }
            //return nameStrings;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{  //关闭连接
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return nameStrings;
    }

}

2. JDBCRegister类,账号密码注册类;向数据库中插入账号和密码。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import com.mysql.jdbc.Driver;

public class JDBCRegister {

    private ResultSet resultSet;
    private Statement statement;
    private Connection connection;

    @Test
    public boolean Register(String usernamestring,String passwordstring){
    boolean success=false;
        //注册驱动 注册mysql驱动
        try {
            DriverManager.registerDriver(new Driver());
            //mysql服务器的地址 jdbc:子协议(mysql)://服务器ip地址:端口(默认3306)/数据库名字
            String url="jdbc:mysql://47.95.193.106:3306/login";
            //访问mysql服务端的用户名
            String username="root";
            //访问mysql服务端的密码
            String password="123456";
            connection = DriverManager.getConnection(url,username, password);
            statement = connection.createStatement();
            String sql="insert into user values ('"+usernamestring+"','"+passwordstring+"');";
            statement.executeUpdate(sql);
            success=true;
            //return nameStrings;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{  //关闭连接
//          try {
//              resultSet.close();
//          } catch (SQLException e) {
//              // TODO Auto-generated catch block
//              e.printStackTrace();
//          }
            try {
                statement.close();
            } catch (SQLException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
            connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return success;
    }

}

3. Register类继承至Servlet类,主要是对从客户端传输的注册数据进行处理操作。

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scong.db.JDBCEqual;
import com.scong.db.JDBCRegister;
import com.scong.db.JdbcHello;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() { 
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ,NullPointerException {
        String usernameString = request.getParameter("username");
        String passwordString = request.getParameter("password");
        JDBCEqual jdbcEqual=new JDBCEqual();
        JDBCRegister jdbcRegister=new JDBCRegister();
        String[] name=jdbcEqual.RegisterEqual();
        PrintWriter writer = response.getWriter();
        if (usernameString == null || passwordString == null
                || usernameString.length() == 0 || passwordString.length() == 0) {
            writer.print("false!");
        } else {
        int i = 0;
        String temp = usernameString;
        for (i = 0; i < name.length; i++) {
            if (temp.equals(name[i])) {
                writer.print("equal");                  
                break;
            }
        }
        if (i==name.length) {
            boolean success=jdbcRegister.Register(usernameString, passwordString);
            writer.print(success);
        }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

8、配置web.xml文件


<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>ServletTestdisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
  <servlet>
    <servlet-name>loginservlet-name>
    <servlet-class>com.scong.servlet.LoginTestservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>loginservlet-name>
    <url-pattern>/loginurl-pattern>
  servlet-mapping>
   <servlet>
    <servlet-name>registerservlet-name>
    <servlet-class>com.scong.servlet.Registerservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>registerservlet-name>
    <url-pattern>/registerurl-pattern>
  servlet-mapping>
web-app>

代码已上传至:http://download.csdn.net/download/sconghw/10154054

你可能感兴趣的:(Android)