溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

android通過web與后臺數(shù)據(jù)庫交互

發(fā)布時間:2020-09-28 08:58:17 來源:網(wǎng)絡(luò) 閱讀:173 作者:2578612215 欄目:移動開發(fā)

1.背景

開發(fā)一個app與后臺數(shù)據(jù)庫交互,基于mysql+jdbc+tomcat,沒有使用DBUtils或jdbc框架,純粹底層jdbc實現(xiàn).
以后逐步改用Spring框架,優(yōu)化mysql,進(jìn)一步部署tomcat等等,現(xiàn)在項目剛剛起步,還有很多不懂的東西,得慢慢來......
這幾天踩了很多坑,說得夸張點真是踩到我沒有知覺,希望能幫助別人少踩坑...

2.開發(fā)環(huán)境

  • 系統(tǒng) : win10
  • IDE : Android Studio 3.5.1,IntelliJ IDEA 2019.02
  • DBMS : Mysql 8.0.17
  • web服務(wù)器: tomcat9

3.相關(guān)資源

  • 1.相關(guān)jar包:
    mysqlV8.0.17驅(qū)動(注意這個要與自己的mysql版本對應(yīng))
    java-servlet-api-V4.0.1
    其他版本可以來這里搜索下載
    Maven倉庫
  • 2.github
    這是源碼地址,包括前后端與建表等所有代碼.
    (歡迎star)

  • 3.碼云
    這也是源碼地址

4.配置開發(fā)環(huán)境

IDE就不說了,重點說一下mysql與tomcat9的安裝

一. 安裝Mysql8.0.17

這個是目前比較新的mysql版本.

服務(wù)器系統(tǒng)是centos
其他系統(tǒng)安裝看這里

  • win10
  • ubuntu
  • fedroa
  • reahat

centos使用yum命令安裝(參考鏈接)

(1) 下載mysql

sudo yum localinstall https://repo.mysql.com//mysql80-community-release-el7-1.noarch.rpm

(2) 安裝mysql

sudo yum install mysql-community-server

(3) 啟動服務(wù)

sudo service mysqld start

(4) 查看初始化密碼,用于下一步設(shè)置自己的root密碼

sudo grep 'temporary password' /var/log/mysqld.log

(5) 本地使用root登錄

mysql -u root -p

輸入上一步看到的密碼

(6) 更改密碼

alter mysql.user 'root'@'localhost' identified by 'password';

注意新版本的mysql不能使用太弱的密碼
如果出現(xiàn)如下提示
android通過web與后臺數(shù)據(jù)庫交互
則說明密碼太弱了,請使用一個更高強度的密碼

(7) 允許外部訪問

use mysql;
update user set host='%' where user='root';

這個可以根據(jù)自己的需要去修改,host='%'表明允許所有的ip登錄,也可以設(shè)置特定的ip,若使用host='%'的話建議新建一個用戶配置相應(yīng)的權(quán)限.

(8) 配置防火墻(可選)

由于作者使用的是阿里云的服務(wù)器,沒配置防火墻的話遠(yuǎn)程連接不上,因此需要手動配置,如圖
android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互

其中授權(quán)對象可以根據(jù)自己的需要更改,0.0.0.0/0表示允許所有的ip.

<br><br>

二.安裝tomcat9

(1) 先去官網(wǎng)下載,下載后上傳文件到服務(wù)器

android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互
作者使用的是scp命令,不會的可以看這里

scp apache-tomcat-xxxx.tar.gz username@xx.xx.xx.xx:/

改成自己的用戶名和ip

(2) 連接到服務(wù)器,解壓壓縮包

mkdir /usr/local/tomcat
mv apache-tomcat-xxxx.tar.gz /usr/local/tomcat
tar -xzvf apache-tomcat-xxx.tar.gz

(3) 修改tomcat默認(rèn)端口(可選)

修改conf/server.xml文件,一般只需修改

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

中的8080端口,修改這個端口即可
這個懶的話(比如作者)可以不改

(4) 啟動tomcat

運行bin目錄下的startup.sh

cd bin
./startup.sh

(5) 測試

瀏覽器輸入

服務(wù)器IP:端口

若出現(xiàn)
android通過web與后臺數(shù)據(jù)庫交互
則表示成功.

(6)開機(jī)啟動

建議配置開機(jī)啟動,修改/etc/rc.local文件

vim /etc/rc.local
添加
sh /usr/local/tomcat/bin/startup.sh

這個根據(jù)自己的tomcat安裝路徑修改,指定bin下的startup.sh即可

5.建庫建表

創(chuàng)建用戶表,這里簡化操作(好吧我喜歡偷懶)就不創(chuàng)建新用戶不授權(quán)了
這是一個在本地用root登錄的示例,請根據(jù)實際情況創(chuàng)建并授權(quán)用戶.

(1) 創(chuàng)建user.sql

CREATE DATABASE userinfo;
USE userinfo;
CREATE TABLE user
(
    id          INT     NOT NULL    PRIMARY KEY   AUTO_INCREMENT,
    name        CHAR(30)    NULL,
    password    CHAR(30)    NULL
);

(2) 導(dǎo)入到數(shù)據(jù)庫

mysql -u root -p < user.sql

android通過web與后臺數(shù)據(jù)庫交互

6.后端部分

(1) 創(chuàng)建項目

選擇web application
android通過web與后臺數(shù)據(jù)庫交互
選好路徑,改好名字后finish
android通過web與后臺數(shù)據(jù)庫交互

(2) 添加jar包

創(chuàng)建一個叫l(wèi)ib的目錄
android通過web與后臺數(shù)據(jù)庫交互
添加兩個jar包:
mysql-connector-java-8.0.17.jar
javax.servlet-api-4.0.1.jar
android通過web與后臺數(shù)據(jù)庫交互
打開Project Structure
android通過web與后臺數(shù)據(jù)庫交互
Modules--> + --> JARs or directories
android通過web與后臺數(shù)據(jù)庫交互
選擇剛才新建的lib下的兩個jar包
android通過web與后臺數(shù)據(jù)庫交互
打勾,apply
android通過web與后臺數(shù)據(jù)庫交互

(3) 創(chuàng)建包與類

總共4個包

  • com.servlet
    用于處理來自前端的請求,包含SignUp.java,SignIn.java
  • com.util
    主要功能是數(shù)據(jù)庫連接,包含DBUtils.java
  • com.entity
    用戶類,包含User.java
  • com.dao
    操作用戶類的類,包含UserDao.java
    android通過web與后臺數(shù)據(jù)庫交互

(4) 先來處理DBUtils類

這個是連接數(shù)據(jù)庫的類,純粹的底層jdbc實現(xiàn),注意驅(qū)動版本.

package com.util;
import java.sql.*;

public class DBUtils {

    private static Connection connection = null;
    public static Connection getConnection()
    {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/數(shù)據(jù)庫名字";
            String usename = "賬號";
            String password = "密碼";
            connection = DriverManager.getConnection(url,usename,password);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return connection;
    }

    public static void closeConnection()
    {
        if(connection != null)
        {
            try {
                connection.close();
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}

主要就是獲取連接與關(guān)閉連接兩個函數(shù).

String url = "jdbc:mysql://127.0.0.1:3306/數(shù)據(jù)庫名字";
String usename = "賬號";
String password = "密碼";

這幾行根據(jù)自己的用戶名,密碼,服務(wù)器ip和庫名修改

注意,mysql8.0以上使用的注冊驅(qū)動的語句是

Class.forName("com.mysql.cj.jdbc.Driver");

舊版的是

Class.forName("com.mysql.jdbc.Driver");

注意對應(yīng).

(5) 接下來處理User類

User類比較簡單,就是就三個字段與getter,setter

package com.entity;

public class User {
    private int id;
    private String name;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

(6) 接下來是UserDao

package com.dao;

import com.entity.User;
import com.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public boolean query(User user)
    {
        Connection connection = DBUtils.getConnection();
        String sql = "select * from user where name = ? and password = ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getName());
            preparedStatement.setString(2,user.getPassword());
            ResultSet resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
        finally {
            DBUtils.closeConnection();
        }
    }

    public boolean add(User user)
    {
        Connection connection = DBUtils.getConnection();
        String sql = "insert into user(name,password) values(?,?)";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getName());
            preparedStatement.setString(2,user.getPassword());
            preparedStatement.executeUpdate();
            return preparedStatement.getUpdateCount() != 0;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return false;
        }
        finally {
            DBUtils.closeConnection();
        }
    }
}

主要就是查詢與添加操作,查詢操作中存在該用戶就返回true,否則返回false
添加操作中使用executeUpdate()與getUpdateCount() != 0.注意不能直接使用

 return preparedStatement.execute();

去代替

preparedStatement.executeUpdate();
return preparedStatement.getUpdateCount() != 0;

咋一看好像沒有什么問題,那天晚上我測試的時候問題可大了,android那邊顯示注冊失敗,但是數(shù)據(jù)庫這邊的卻insert進(jìn)去了.........我......
好吧說多了都是淚,還是函數(shù)用得不夠熟練.<br><br>

  • 一般來說select使用executeQuery()
    executeQuery()返回ResultSet,表示結(jié)果集,保存了select語句的執(zhí)行結(jié)果,配合next()使用
  • delete,insert,update使用executeUpdate()
    executeUpdate()返回的是一個整數(shù),表示受影響的行數(shù),即delete,insert,update修改的行數(shù),對于drop,create操作返回0
  • create,drop使用execute()
    execute()的返回值是這樣的:
    • 如果第一個結(jié)果是ResultSet對象,則返回true
    • 如果第一個結(jié)果是更新計數(shù)或者沒有結(jié)果則返回false

所以在這個例子中

 return preparedStatement.execute();

肯定返回false,所以才會數(shù)據(jù)庫這邊insert進(jìn)去,但前端顯示注冊失敗(這個bug作者找了很久......)

(7) servlet包的SignIn與SignUp類

SingIn類用于處理登錄,調(diào)用jdbc查看數(shù)據(jù)庫是否有對應(yīng)的用戶
SignUp類用于處理注冊,把user添加到數(shù)據(jù)庫中
這兩個使用的是http連接,后期作者會采用https加密連接.

SignIn.java

package com.servlet;

import com.dao.UserDao;
import com.entity.User;

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 java.io.IOException;

@WebServlet("/SignIn")
public class SingIn extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException,ServletException
    {
        this.doPost(httpServletRequest,httpServletResponse);
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException, ServletException
    {
        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("text/plain;charset=utf-8");//設(shè)置相應(yīng)類型為html,編碼為utf-8

        String name = httpServletRequest.getParameter("name");
        String password = httpServletRequest.getParameter("password");

        UserDao userDao = new UserDao();
        User user = new User();
        user.setName(name);
        user.setPassword(password);

        if(!userDao.query(user))//若查詢失敗
        {
            httpServletResponse.sendError(204,"query failed.");//設(shè)置204錯誤碼與出錯信息
        }
    }
}
@WebServlet("/SignIn")

這行代碼表示這是一個名字叫SignIn的servlet,可用于實現(xiàn)servlet與url的映射,如果不在這里添加這個注解,則需要在WEB-INF目錄下的web.xml添加一個

<servlet-mapping>

叫servlet的映射

httpServletResponse.setContentType("text/plain;charset=utf-8");//設(shè)置相應(yīng)類型為html,編碼為utf-8

這行代碼設(shè)置響應(yīng)類型與編碼

String name = httpServletRequest.getParameter("name");
String password = httpServletRequest.getParameter("password");

HttpServletRequest.getParameter(String name)方法表示根據(jù)name獲取相應(yīng)的參數(shù)

下面是SignUp.java

package com.servlet;

import com.dao.UserDao;
import com.entity.User;

import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.IOException;

@WebServlet("/SignUp")
public class SignUp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException,ServletException
    {
        this.doPost(httpServletRequest,httpServletResponse);
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException,ServletException
    {
        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");//設(shè)定編碼防止中文亂碼
        httpServletResponse.setContentType("text/plain;charset=utf-8");//設(shè)置相應(yīng)類型為html,編碼為utf-8

        String name = httpServletRequest.getParameter("name");//根據(jù)name獲取參數(shù)
        String password = httpServletRequest.getParameter("password");//根據(jù)password獲取參數(shù)

        UserDao userDao = new UserDao();
        User user = new User();
        user.setName(name);
        user.setPassword(password);

        if(!userDao.add(user)) //若添加失敗
        {
            httpServletResponse.sendError(204,"add failed.");//設(shè)置204錯誤碼與出錯信息
        }
    }
}

(8) 添加servlet到web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>SignIn</servlet-name>
        <servlet-class>com.servlet.SingIn</servlet-class>
    </servlet>

    <servlet>
        <servlet-name>SignUp</servlet-name>
        <servlet-class>com.servlet.SignUp</servlet-class>
    </servlet>
</web-app>

要把剛才創(chuàng)建的Servlet添加進(jìn)web.xml,在<servlet>中添加子元素<servlet-name>與<servlet-class>
<servlet-name>是Servlet的名字,最好與類名一致.
<servlet-class>是Servlet類的位置.
如果在Servlet類中沒有添加

@WebServlet("/xxxx")

這個注解,則需要在web.xml中添加

<servlet-mapping>
    <servlet-name>SignIn</servlet-name>
    <url-pattern>/SignIn</url-pattern>
</servlet-mapping>

其中<servlet-name>與<servlet>中的子元素<servlet-name>中的值一致
<url-pattern>是訪問的路徑

(9) 最后添加一個叫Hello.html的html文件用于測試.

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head>
    <body>
        Hello web.
    </body>
</html>

<br><br><br>

7.打包發(fā)布

作者用的是IDEA,Eclipse的打包請看這里

(1) 打開project structure

android通過web與后臺數(shù)據(jù)庫交互

(2) 選擇Artifacts,Web Application:Archive

android通過web與后臺數(shù)據(jù)庫交互

(3) 改名字,創(chuàng)建WEB-INF目錄與子目錄classes

android通過web與后臺數(shù)據(jù)庫交互

(4) 選中classes,添加Module Output,選擇自己的web項目

android通過web與后臺數(shù)據(jù)庫交互

(5) 添加jar包,選中l(wèi)ib目錄后添加jar包文件

(那個lib文件夾被擋住了.....)
android通過web與后臺數(shù)據(jù)庫交互

(6) 添加Hello.html與web.xml

web.xml這個需要在WEB-INF目錄里,Hello.html在WEB-INF外面
android通過web與后臺數(shù)據(jù)庫交互

(7) 打包,Build->Build Artifacts

android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互

(8) 上傳到服務(wù)器

把打包好的.war文件上傳到服務(wù)器的tomcat的/webapps目錄下的

scp ***.war username@xxx.xxx.xxx.xxx:/usr/local/tomcat/webapps

注意改成自己的webapps目錄.

(9) 測試

在瀏覽器輸入

服務(wù)器IP:端口/項目/Hello.html

作者是在本地上開了tomcat后測試的
android通過web與后臺數(shù)據(jù)庫交互

8.前端頁面部分

(1) 新建工程

android通過web與后臺數(shù)據(jù)庫交互
android通過web與后臺數(shù)據(jù)庫交互

(2) MainActivity.java

package com.cx;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button signin = (Button) findViewById(R.id.signin);
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = ((EditText) findViewById(R.id.etname)).getText().toString();
                String password = ((EditText) findViewById(R.id.etpassword)).getText().toString();
                if (UserService.signIn(name, password))
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

        Button signup = (Button) findViewById(R.id.signup);
        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = ((EditText) findViewById(R.id.etname)).getText().toString();
                String password = ((EditText) findViewById(R.id.etpassword)).getText().toString();
                if (UserService.signUp(name, password))
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "注冊成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "注冊失敗", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }
}

沒什么好說的,就為兩個Button綁定事件,然后設(shè)置兩個Toast提示信息.

(3) UserService.java

package com.cx;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class UserService {
    public static boolean signIn(String name, String password) {
        MyThread myThread = new MyThread("http://本機(jī)IP:8080/cx/SignIn",name,password);
        try
        {
            myThread.start();
            myThread.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        return myThread.getResult();
    }

    public static boolean signUp(String name, String password) {
        MyThread myThread = new MyThread("http://本機(jī)IP:8080/cx/SignUp",name,password);
        try
        {
            myThread.start();
            myThread.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return myThread.getResult();
    }
}

class MyThread extends Thread
{
    private String path;
    private String name;
    private String password;
    private boolean result = false;

    public MyThread(String path,String name,String password)
    {
        this.path = path;
        this.name = name;
        this.password = password;
    }
    @Override
    public void run()
    {
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(8000);//設(shè)置連接超時時間
            httpURLConnection.setReadTimeout(8000);//設(shè)置讀取超時時間
            httpURLConnection.setRequestMethod("POST");//設(shè)置請求方法,post

            String data = "name=" + URLEncoder.encode(name, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");//設(shè)置數(shù)據(jù)
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//設(shè)置響應(yīng)類型
            httpURLConnection.setRequestProperty("Content-Length", data.length() + "");//設(shè)置內(nèi)容長度
            httpURLConnection.setDoOutput(true);//允許輸出
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data.getBytes("utf-8"));//寫入數(shù)據(jù)
            result = (httpURLConnection.getResponseCode() == 200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean getResult()
    {
        return result;
    }
}
MyThread myThread = new MyThread("http://本機(jī)IP:8080/cx/SignUp",name,password);
MyThread myThread = new MyThread("http://本機(jī)IP:8080/cx/SignIn",name,password);

這兩行換成自己的ip,本地ip的話可以用ipconfig或ifconfig查看,修改了默認(rèn)端口的話也把端口一起改了.
路徑的話就是

端口/web項目名/Servlet名

web項目名是再打成war包時設(shè)置的,Servlet名在web.xml中的<servlet>的子元素<servlet-name>設(shè)置,與java源碼中的@WebServlet()注解中的一致

另外一個要注意的就是線程問題,需要新開一個線程進(jìn)行http的連接

(4) activity_main.xml

前端頁面部分很簡單,就兩個button,用于驗證功能.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用戶名"
            />
        <EditText
            android:layout_width="300dp"
            android:layout_height="60dp"
            android:id="@+id/etname"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密碼"
            />
        <EditText
            android:layout_width="300dp"
            android:layout_height="60dp"
            android:id="@+id/etpassword"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="120dp"
            android:layout_height="60dp"
            android:text="注冊"
            android:id="@+id/signup"
            />
        <Button
            android:layout_width="120dp"
            android:layout_height="60dp"
            android:text="登錄"
            android:id="@+id/signin"
            />
    </LinearLayout>
</LinearLayout>

9.測試

(1) 注冊測試

隨便輸入用戶名與密碼
android通過web與后臺數(shù)據(jù)庫交互

查看數(shù)據(jù)庫
android通過web與后臺數(shù)據(jù)庫交互
這里沒有加密保存,后期會添加加密保存

(2) 登錄測試

android通過web與后臺數(shù)據(jù)庫交互
perfect!

10.注意事項

(1) 數(shù)據(jù)庫的用戶名和密碼一定要設(shè)置正確,要不然會這樣提示

android通過web與后臺數(shù)據(jù)庫交互
這個錯誤在加載驅(qū)動錯誤時也可能會出現(xiàn)這個錯誤,因此要確保打成war包時lib目錄正確且jar包版本正確.
還有就是由于這個是jdbc的底層實現(xiàn),注意手寫的sql語句不能錯
千萬千萬別像我這樣:
android通過web與后臺數(shù)據(jù)庫交互

(2) 網(wǎng)絡(luò)權(quán)限問題

這個需要在AndroidManifest.xml添加網(wǎng)絡(luò)權(quán)限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

(3) 防火墻問題

服務(wù)器的話一般會有相應(yīng)的相應(yīng)的網(wǎng)頁界面配置,比如作者的是阿里云服務(wù)器,當(dāng)然也可以手動配置iptables
修改/etc/sysconfig/iptables

vim /etc/sysconfig/iptables

添加

-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT

重啟iptables

service iptables restart

(4) 使用HTTP注意事項

由于從Android P開始,google默認(rèn)要求使用加密連接,即要使用HTTPS,所以會禁止使用HTTP連接
使用HTTP連接時會出現(xiàn)以下異常

 W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
 java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy

兩種建議:

1 使用HTTPS
2 修改默認(rèn)的AndroidManifest.xml使其允許HTTP連接

在res下新建一個文件夾xml,創(chuàng)建一個叫network_security_config.xml的文件,文件內(nèi)容如下

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

然后在AndroidMainfest.xml中加入

<application
 android:networkSecurityConfig="@xml/network_security_config"
/>

即可

另一種辦法是直接加入一句

android:usesCleartextTraffic="true"
<application 
android:usesCleartextTraffic="true"
/>

(5) 線程問題

從android4.0開始,聯(lián)網(wǎng)不能再主線程操作,萬一網(wǎng)絡(luò)不好就會卡死,所以有關(guān)聯(lián)網(wǎng)的操作都需要新開一個線程,不能在主線程操作.

(6) AVD問題

android通過web與后臺數(shù)據(jù)庫交互
這個bug作者找了很久,http連接沒問題,服務(wù)器沒問題,數(shù)據(jù)庫沒問題,前端代碼沒問題,然后去了stackoverflow,發(fā)現(xiàn)是AVD的問題,我.......
android通過web與后臺數(shù)據(jù)庫交互
簡單來說就是卸載了再重啟AVD,居然成功了.....

參考網(wǎng)站
1.Android 通過Web服務(wù)器與Mysql數(shù)據(jù)庫交互
2.Android高版本聯(lián)網(wǎng)失敗
3.IDEA 部署Web項目
4.PreparedStatement的executeQuery、executeUpdate和execute
5.preparedstatement execute()操作成功!但是返回false
6.HttpServletResponse(一)
7.HttpServletResponse(二)
8.HttpServletRequest
9.HttpUrlConnection
10.java.net.socketexception

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI