【android】android+okhttp+java服务端(tomcat)+mysql实现登录注册

【android】android+okhttp+java服务端(tomcat)+mysql实现登录注册,第1张

先上代码(文章结尾有遇到的问题和对应解决方案) android客户端 >android:app-build.gradle

1.添加okhttp依赖,具体根据自己的okhttp包来决定

dependencies {
	...
	implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okio:okio:1.5.0'
}
>android:app-src-res

1.新建XML文件,文件名network_security_config


<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
network-security-config>
>android:AndroidManifast.xml

1.添加网络权限

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

2.添加网络配置第1步和第2步

<application
...
android:usesCleartextTraffic="false"
android:networkSecurityConfig="@xml/network_security_config">
>android:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_margin="10dp">
<EditText
    android:id="@+id/loginAccount_etext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:hint="请输入账号"/>
<EditText
    android:id="@+id/loginPassword_etext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:hint="请输入密码"/>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
        android:id="@+id/loginBtn"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="登录"/>
    <Button
        android:id="@+id/registerBtn"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="注册"/>
LinearLayout>
LinearLayout>
>android:MainActivity.java
package com.example.okhttptest;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        loginAccount_etext = findViewById(R.id.loginAccount_etext);
        loginPassword_etext = findViewById(R.id.loginPassword_etext);
        Button loginBtn = findViewById(R.id.loginBtn);
        Button registerBtn = findViewById(R.id.registerBtn);
        registerBtn.setOnClickListener(this);
        loginBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.loginBtn:
                String loginAddress="http://192.168.1.104:9977/Okhttptest/LoginServlet?";
                //http://电脑ip地址:tomcat端口号/java项目名/类名?
                String loginAccount = loginAccount_etext.getText().toString();
                String loginPassword = loginPassword_etext.getText().toString();
                loginWithOkHttp(loginAddress,loginAccount,loginPassword);
                break;
            case R.id.registerBtn:
                String registerAddress="http://192.168.1.104:9977/Okhttptest/RegisterServlet?";
                //http://电脑ip地址:tomcat端口号/java项目名/类名?
                String registerAccount = loginAccount_etext.getText().toString();
                String registerPassword = loginPassword_etext.getText().toString();
                registerWithOkHttp(registerAddress,registerAccount,registerPassword);
                break;
            default:
                break;
        }
    }

    //实现登录
    public void loginWithOkHttp(String address,String account,String password){
        HttpUtil.loginWithOkHttp(address,account,password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                final String responseData = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (responseData.equals("true")){
                            Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    //实现注册
    public void registerWithOkHttp(String address,String account,String password){
        HttpUtil.registerWithOkHttp(address, account, password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (responseData.equals("true")){
                            Toast.makeText(MainActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }
}
>android:HttpUtil.java
package com.example.okhttptest;


import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

class HttpUtil {
    //登录
    static void loginWithOkHttp(String address,String account,String password,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("loginAccount",account)
                .add("loginPassword",password)
                .build();
        Request request = new Request.Builder()
                .url(address)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
    //注册
    static void registerWithOkHttp(String address,String account,String password,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("registerAccount",account)
                .add("registerPassword",password)
                .build();
        Request request = new Request.Builder()
                .url(address)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
}
mysql数据库 >新建数据库lolbox,新建表userinfo(两个字段:(varchar2)account和(varchar2)password)

java服务端 >新建Dynamic Web Project项目 >添加mysql-connector-java-8.0.28.jar包

根据自己的下载的版本为主

>在WebContent文件夹下新建index.jsp文件
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Insert title here</title>
	</head>
	<body>
	<h1>服务端已开启</h1>
	</body>
</html>
>创建com.henuajy.Entity包,User.java
package com.henuajy.Entity;
 
public class User {
    private String loginAccount;
    private String loginPassword;
 
    public User(String loginAccount,String loginPassword){
        this.loginAccount = loginAccount;
        this.loginPassword = loginPassword;
    }
 
    public String getLoginAccount() {
        return loginAccount;
    }
 
    public void setLoginAccount(String loginAccount) {
        this.loginAccount = loginAccount;
    }
 
    public String getLoginPassword() {
        return loginPassword;
    }
 
    public void setLoginPassword(String loginPassword) {
        this.loginPassword = loginPassword;
    }
}
>创建com.henuajy.Model包,LoginModel.java
package com.henuajy.Model;
 
import com.henuajy.Entity.User;
import java.sql.*;
 
public class LoginModel {
    private static String DBUNAME = "root";
    private static String DBUPWD = "1911411206";
    //输入自己的mysql数据库的密码
    private static String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static String URL = "jdbc:mysql://localhost:3306/lolbox?"
    		+ "serverTimezone=UTC"
    		+ "&useUnicode=true&characterEncoding=utf-8"
    		+ "&zeroDateTimeBehavior=convertToNull"
    		+ "&useSSL=false"
    		+ "&allowPublicKeyRetrieval=true";
 	/*URL="jdbc:mysql://localhost:3306/数据库名(?设置时区
 	/指定字符的编码、解码格式
 	/在 *** 作各项值均为0时,转化为null
 	/禁用SSL
 	/允许客户端从服务器获取公钥)"*/
 	
    public static boolean login(User user){
        String loginAccount = user.getLoginAccount();
        String loginPassword = user.getLoginPassword();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;
        try{
            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL,DBUNAME,DBUPWD);
            pstmt = con.prepareStatement("select count(*)from userinfo where account=? and password=?");
            pstmt.setString(1,loginAccount);
            pstmt.setString(2,loginPassword);
            rs = pstmt.executeQuery();
            if (rs.next()){
                count = rs.getInt(1);
                System.out.println("链接成功");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try{
                if (rs!=null){
                    rs.close();
                }
                if (pstmt!=null){
                    pstmt.close();
                }
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (count==1){
                return true;
            }else{
                return false;
            }
        }
    }
 
    public static boolean register(User user){
        String loginAccount = user.getLoginAccount();
        String loginPassword = user.getLoginPassword();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;
        try{
            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL,DBUNAME,DBUPWD);
            pstmt = con.prepareStatement("insert into userinfo values (?,?)");
            pstmt.setString(1,loginAccount);
            pstmt.setString(2,loginPassword);
            count = pstmt.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try{
                if (rs!=null){
                    rs.close();
                }
                if (pstmt!=null){
                    pstmt.close();
                }
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (count==1){
                return true;
            }else{
                return false;
            }
        }
    }
}
>创建com.henuajy.Servlet包 >LoginServlet.java
package com.henuajy.Servlet;
 
import com.henuajy.Entity.User;
import com.henuajy.Model.LoginModel;
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;
import java.io.PrintWriter;
 
@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
        doGet(request,response);
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String loginAccount = request.getParameter("loginAccount");
        String loginPassword = request.getParameter("loginPassword");
        User user = new User(loginAccount,loginPassword);
        boolean result = LoginModel.login(user);
        System.out.println("登录账号:"+loginAccount+",登陆密码:"+loginPassword+",登录结果"+result);
        response.setCharacterEncoding("UTF-8");
        
        //通过PrintWriter返回给客户端 *** 作结果
        PrintWriter writer = response.getWriter();
        writer.print(result);
    }
}
>RegisterServlet.java
package com.henuajy.Servlet;
 
import com.henuajy.Entity.User;
import com.henuajy.Model.LoginModel;
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;
import java.io.PrintWriter;
 
@WebServlet(name = "RegisterServlet",value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
        doGet(request,response);
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
        //request.setCharacterEncoding("utf-8");
        String registerAccount = request.getParameter("registerAccount");
        String registerPassword = request.getParameter("registerPassword");
        User registerUser = new User(registerAccount,registerPassword);
        boolean rs = LoginModel.register(registerUser);
        System.out.println("注册账号:"+registerAccount+",注册密码:"+registerPassword+",注册结果"+rs);
        //通过PrintWriter返回给客户端 *** 作结果
        PrintWriter writer = response.getWriter();
        writer.print(rs);
    }
}
遇到的问题 安装mysql

我参考的答案

PS:mysql最基础的是黑框版如下,可以下载可视化工具如Navicat等,也可以不下。

java链接mysql的jar包

官网下载

电脑ip地址

Windows+R输入cmd,输入ipconfig。如果是宽带联网就是以太网的IPv4 地址;如果是WiFi链接就是无线局域网的IPv4 地址

链接服务端时填写的端口号
String loginAddress="http://192.168.1.104:9977/Okhttptest/LoginServlet?";

因为是Tomcat发布所以端口号要以这个为准,不一定是8080

如果发现有内容错误处,评论指出,教学相长,感激不尽。
有其他疑问,指出即讨论改正。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存