Android客户端连接阿里云服务器MySQL数据库实现登录功能(代码配置流程详解)

如果对Android连接服务器原理以及流程不了解同学可以先看看我的这篇分析连接流程的博客

Android连接服务器流程详解

下面是代码部分,解释一下用到的技术,客户端采用最原始的HttpUrlConnnection,服务器端用的Servlet,现在我不建议采用这样的技术了。
客户端使用Okhttp,服务器端使用Struts框架即可。

配置

客户端 android studio 3.2 +netBeans(编写Java web的小众软件,MyEclipse也可以)

服务器 windows server 2012R2版 +XAMMP(Apache+MySQL+PHP+tomacat集成软件包)+MySQL-Front

客户端代码
Activity-login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:text="登录测试"
        android:textSize="40dp"
        android:textColor="#003399"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:gravity="center_horizontal"
        android:layout_margin="10dp"/>


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:hint="账号"
        android:textColorHint="#003399"
        android:id="@+id/login_edit_account"
        android:textSize="20dp"
        android:textColor="#003399"
        android:layout_margin="10dp"/>



    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:hint="密码"
        android:textColorHint="#003399"
        android:id="@+id/login_edit_pwd"
        android:textSize="20dp"
        android:textColor="#003399"
        android:layout_margin="10dp"/>

    <Button
        android:text="登录"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/login_btn_login"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#0099FF"/>
</LinearLayout>

LogindemoActivity

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class LoginDemoActivity extends AppCompatActivity {
    /** Called when the activity is first created. */
    private Button loginBtn;

    private EditText inputUsername;
    private EditText inputPassword;

    private String responseMsg = "";
    private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟
    private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟
    private static final int LOGIN_OK = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_demo);
        loginBtn = (Button)findViewById(R.id.login_btn_login);

        inputUsername = (EditText)findViewById(R.id.login_edit_account);
        inputPassword = (EditText)findViewById(R.id.login_edit_pwd);

       
        loginBtn.setOnClickListener(new Button.OnClickListener()
        {

            @Override
            public void onClick(View v) {
                Thread loginThread = new Thread(new LoginThread());

                loginThread.start();
            }



        });


    }


    private boolean loginServer(String username, String password)
    {
        boolean loginValidate = false;
        //使用apache HTTP客户端实现
        String urlStr = "http://服务器IP/Javaweb项目名/LoginServlet";
        HttpPost request = new HttpPost(urlStr);
       
        List<NameValuePair> params = new ArrayList<NameValuePair>();
      
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("password",password));
        try
        {
            //设置请求参数项
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpClient client = getHttpClient();
            //执行请求返回相应
            HttpResponse response = client.execute(request);

            //判断是否请求成功
            if(response.getStatusLine().getStatusCode()==200)
            {
                loginValidate = true;
                //获得响应信息
                responseMsg = EntityUtils.toString(response.getEntity());
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return loginValidate;
    }



    //初始化HttpClient
    public HttpClient getHttpClient()
    {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }

    //Handler
    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case 0:


                    Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();

                    break;
                case 1:

                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                    break;
                case 2:

                    Toast.makeText(getApplicationContext(), "URL错误", Toast.LENGTH_SHORT).show();
                    break;

            }

        }
    };

    //LoginThread线程类
    class LoginThread implements Runnable
    {

        @Override
        public void run() {
            String username = inputUsername.getText().toString();
            String password = inputPassword.getText().toString();
            System.out.println("username="+username+":password="+password);

            //URL合法,但是这一步并不验证密码是否正确
            boolean loginValidate = loginServer(username, password);
            System.out.println("-----------bool is :"+loginValidate+"----------response:"+responseMsg);
            Message msg = handler.obtainMessage();
            if(loginValidate)
            {
                if(responseMsg.equals("true"))
                {
                    msg.what = 0;
                    handler.sendMessage(msg);
                }else
                {
                    msg.what = 1;
                    handler.sendMessage(msg);
                }

            }else
            {
                msg.what = 2;
                handler.sendMessage(msg);
            }
        }

    }


}

整个客户端就一个LogindemoActivity和acticity_login布局文件,注意导入httpClient的方法

导入httpClient
Gradle.script—>build gradle(module:app)

第一步:
在androd{…}里面加上这句:

 useLibrary'org.apache.http.legacy'

第二步:如果报错Classnotfound,试试这个加进去把原来的替换掉

 implementation 'com.android.support:appcompat-v7:26.0+'

这里是因为你自己使用的不匹配或者不兼容导致的错误

改完以后代码如下:

android {
    compileSdkVersion 28
    useLibrary'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.example.yang.test"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0+'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

第三步:记得在配置文件里面加网络权限

配置文件代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yang.test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginDemoActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>

客户端的代码都在这里,没错了!

服务器代码

至于服务器的初始化搭建可以参考我的另外两篇博客

Windows server 2012 R2的测试(访问一张图片为例)
阿里云windows server 2012R2服务器的搭建+Tomcat(访问一张照片为例)

如果你的服务器还不能被外界访问,那就不要说访问服务器的数据库了,服务器能被外网访问了,我们再来看看怎么布置服务器!

一。搭建数据库
我们选择MySQL-Front,优点就是小巧好用
下载后安装我就不说了,来构建一个数据库!

  1. 右键localhost—>新建—>数据库
  2. 写好数据库名,字符集选择utf8,字符集校对不改动
  3. 右键新建的数据库—>新建—>表格
  4. 填好表名,其他不改动,确定就行
  5. 右键表—>新建字段—>UserName(在Id之后,varchar,长度64就行,确定)和Password(同上)
  6. 最后还要打开访问这张表的权限,双击用户—>右键@localhost—>属性—>权限—>新建—选择数据库—增删改查四个权限都勾选,确定就行
  7. 补充一句,如果不小心把mysql数据库删除了,没有什么好办法恢复,初始服务器磁盘是最快的方法

表建好了,下一步写Java web的代码!!

二.Servelet代码
我用的是netBeans,用Java EE也行,直接贴代码先!

DBManager.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class DBManager extends HttpServlet {

    ServletConfig config;                             //定义一个ServletConfig对象
    private static String UserName;                   //定义的数据库用户名
    private static String Password;                   //定义的数据库连接密码
    private static String url="jdbc:mysql://localhost:3306/....;             //填你的数据库名
    private static Connection connection;             //定义连接

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);                                  //继承父类的init()方法
        this.config = config;                                //获取配置信息
        UserName = config.getInitParameter("DBUsername");    //获取数据库用户名
        Password = config.getInitParameter("DBPassword");    //获取数据库连接密码
        url = config.getInitParameter("ConnectionURL");      //获取数据库连接URL
    }

    /**
     * 获得数据库连接对象
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(url, UserName, Password);
        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException | SQLException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }

    /**
     * 关闭所有的数据库连接资源
     *
     * @param connection Connection 链接
     * @param statement Statement 资源
     * @param resultSet ResultSet 结果集合
     */
    public static void closeAll(Connection connection, Statement statement,
            ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

User.java

public class User {

    //用户姓名
    private String UserName;

    //用户密码
    private String Password;

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        this.UserName = userName;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String password) {
        this.Password = password;
    }
}

UserDAO.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

/**
 * 数据库管理类,提供连接数据库和拆解链接功能
 *
 * @author Implementist
 */
public class DBManager extends HttpServlet {

    ServletConfig config;                             //定义一个ServletConfig对象
    private static String UserName;                   //定义的数据库用户名
    private static String Password;                   //定义的数据库连接密码
    private static String url="jdbc:mysql://localhost:3306/myfirstapp";                        //定义数据库连接URL
    private static Connection connection;             //定义连接

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);                                  //继承父类的init()方法
        this.config = config;                                //获取配置信息
        UserName = config.getInitParameter("DBUsername");    //获取数据库用户名
        Password = config.getInitParameter("DBPassword");    //获取数据库连接密码
        url = config.getInitParameter("ConnectionURL");      //获取数据库连接URL
    }

    /**
     * 获得数据库连接对象
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(url, UserName, Password);
        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException | SQLException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }

    /**
     * 关闭所有的数据库连接资源
     *
     * @param connection Connection 链接
     * @param statement Statement 资源
     * @param resultSet ResultSet 结果集合
     */
    public static void closeAll(Connection connection, Statement statement,
            ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

LoginServlet

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

/**
 * 测试登录Servlet
 *
 * @author Implementist
 */
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应内容类型  
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        try (PrintWriter out = response.getWriter()) {

            //获得请求中传来的用户名和密码
            String accountNumber = request.getParameter("username").trim();
            String password = request.getParameter("password").trim();

            //密码验证结果
            Boolean verifyResult = verifyLogin(accountNumber, password);

            Map<String, String> params = new HashMap<>();
            JSONObject jsonObject = new JSONObject();

          if (verifyResult) {
                out.print(true);
            } else {
                out.print(false);
            }

          
        }
    }

  
    /**
     * 验证用户名密码是否正确
     *
     * @param userName
     * @param password
     */
    private Boolean verifyLogin(String userName, String password) {
        User user = UserDAO.queryUser(userName);

        //账户密码验证
        return null != user && password.equals(user.getPassword());
    }
}

doGet代码是自动生成的别改动就行了,添加各种JARs文件,清理并构建项目,找到生成的.war文件上传至tomcat/webapps/的路径下就可以了,剩下的测试就行了,贴图在这里插入图片描述

整个流程就是这样,有问题评论我会及时回复

在下的资源分享群,欢迎各位!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43927892/article/details/88144863