欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

1.背景

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

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊(cè)、網(wǎng)絡(luò)空間、營(yíng)銷(xiāo)軟件、網(wǎng)站建設(shè)、丹鳳網(wǎng)站維護(hù)、網(wǎng)站推廣。

2.開(kāi)發(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ū)動(dòng)(注意這個(gè)要與自己的mysql版本對(duì)應(yīng))
    java-servlet-api-V4.0.1
    其他版本可以來(lái)這里搜索下載
    Maven倉(cāng)庫(kù)
  • 2.github
    這是源碼地址,包括前后端與建表等所有代碼.
    (歡迎star)

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

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

IDE就不說(shuō)了,重點(diǎn)說(shuō)一下mysql與tomcat9的安裝

一. 安裝Mysql8.0.17

這個(gè)是目前比較新的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) 啟動(dòng)服務(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通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
則說(shuō)明密碼太弱了,請(qǐng)使用一個(gè)更高強(qiáng)度的密碼

(7) 允許外部訪問(wèn)

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

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

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

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

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

<br><br>

二.安裝tomcat9

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

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

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端口,修改這個(gè)端口即可
這個(gè)懶的話(比如作者)可以不改

(4) 啟動(dòng)tomcat

運(yùn)行bin目錄下的startup.sh

cd bin
./startup.sh

(5) 測(cè)試

瀏覽器輸入

服務(wù)器IP:端口

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

(6)開(kāi)機(jī)啟動(dòng)

建議配置開(kāi)機(jī)啟動(dòng),修改/etc/rc.local文件

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

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

5.建庫(kù)建表

創(chuàng)建用戶表,這里簡(jiǎn)化操作(好吧我喜歡偷懶)就不創(chuàng)建新用戶不授權(quán)了
這是一個(gè)在本地用root登錄的示例,請(qǐng)根據(jù)實(shí)際情況創(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ù)庫(kù)

mysql -u root -p < user.sql

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

6.后端部分

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

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

(2) 添加jar包

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

(3) 創(chuàng)建包與類(lèi)

總共4個(gè)包

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

(4) 先來(lái)處理DBUtils類(lèi)

這個(gè)是連接數(shù)據(jù)庫(kù)的類(lèi),純粹的底層jdbc實(shí)現(xiàn),注意驅(qū)動(dòng)版本.

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ù)庫(kù)名字";
            String usename = "賬號(hào)";
            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)閉連接兩個(gè)函數(shù).

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

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

注意,mysql8.0以上使用的注冊(cè)驅(qū)動(dòng)的語(yǔ)句是

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

舊版的是

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

注意對(duì)應(yīng).

(5) 接下來(lái)處理User類(lèi)

User類(lèi)比較簡(jiǎn)單,就是就三個(gè)字段與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) 接下來(lái)是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;

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

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

所以在這個(gè)例子中

 return preparedStatement.execute();

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

(7) servlet包的SignIn與SignUp類(lèi)

SingIn類(lèi)用于處理登錄,調(diào)用jdbc查看數(shù)據(jù)庫(kù)是否有對(duì)應(yīng)的用戶
SignUp類(lèi)用于處理注冊(cè),把user添加到數(shù)據(jù)庫(kù)中
這兩個(gè)使用的是http連接,后期作者會(huì)采用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)類(lèi)型為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錯(cuò)誤碼與出錯(cuò)信息
        }
    }
}
@WebServlet("/SignIn")

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

<servlet-mapping>

叫servlet的映射

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

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

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)類(lèi)型為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錯(cuò)誤碼與出錯(cuò)信息
        }
    }
}

(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的名字,最好與類(lèi)名一致.
<servlet-class>是Servlet類(lèi)的位置.
如果在Servlet類(lèi)中沒(méi)有添加

@WebServlet("/xxxx")

這個(gè)注解,則需要在web.xml中添加

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

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

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

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

<br><br><br>

7.打包發(fā)布

作者用的是IDEA,Eclipse的打包請(qǐng)看這里

(1) 打開(kāi)project structure

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

(2) 選擇Artifacts,Web Application:Archive

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

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

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

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

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

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

(那個(gè)lib文件夾被擋住了.....)
android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

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

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

(7) 打包,Build->Build Artifacts

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

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

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

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

注意改成自己的webapps目錄.

(9) 測(cè)試

在瀏覽器輸入

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

作者是在本地上開(kāi)了tomcat后測(cè)試的
android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

8.前端頁(yè)面部分

(1) 新建工程

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互

(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, "注冊(cè)成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "注冊(cè)失敗", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }
}

沒(méi)什么好說(shuō)的,就為兩個(gè)Button綁定事件,然后設(shè)置兩個(gè)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è)置連接超時(shí)時(shí)間
            httpURLConnection.setReadTimeout(8000);//設(shè)置讀取超時(shí)時(shí)間
            httpURLConnection.setRequestMethod("POST");//設(shè)置請(qǐng)求方法,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)類(lèi)型
            httpURLConnection.setRequestProperty("Content-Length", data.length() + "");//設(shè)置內(nèi)容長(zhǎng)度
            httpURLConnection.setDoOutput(true);//允許輸出
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data.getBytes("utf-8"));//寫(xiě)入數(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項(xiàng)目名/Servlet名

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

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

(4) activity_main.xml

前端頁(yè)面部分很簡(jiǎn)單,就兩個(gè)button,用于驗(yàn)證功能.

<?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="注冊(cè)"
            android:id="@+id/signup"
            />
        <Button
            android:layout_width="120dp"
            android:layout_height="60dp"
            android:text="登錄"
            android:id="@+id/signin"
            />
    </LinearLayout>
</LinearLayout>

9.測(cè)試

(1) 注冊(cè)測(cè)試

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

查看數(shù)據(jù)庫(kù)
android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
這里沒(méi)有加密保存,后期會(huì)添加加密保存

(2) 登錄測(cè)試

android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
perfect!

10.注意事項(xiàng)

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

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

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

這個(gè)需要在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èn)題

服務(wù)器的話一般會(huì)有相應(yīng)的相應(yīng)的網(wǎng)頁(yè)界面配置,比如作者的是阿里云服務(wù)器,當(dāng)然也可以手動(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注意事項(xiàng)

由于從Android P開(kāi)始,google默認(rèn)要求使用加密連接,即要使用HTTPS,所以會(huì)禁止使用HTTP連接
使用HTTP連接時(shí)會(huì)出現(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下新建一個(gè)文件夾xml,創(chuàng)建一個(gè)叫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) 線程問(wèn)題

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

(6) AVD問(wèn)題

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

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

分享名稱:android通過(guò)web與后臺(tái)數(shù)據(jù)庫(kù)交互
網(wǎng)站URL:http://chinadenli.net/article28/gdopcp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化云服務(wù)器、建站公司微信小程序、手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)