android HTTP 登陆链接Mysql数据库实现登陆

android HTTP 链接Mysql数据库实现登陆

1.java web本地服务器,链接数据库实现数据库增、查功能
2.android端通过http访问web服务器

一、web端
1.myeclipse新建java web项目
工程目录
android HTTP 登陆链接Mysql数据库实现登陆_第1张图片
2.web.xml如下配置



  HelloWeb
  
    LogLet
    com.servlet.LogLet
  
  
    RegLet
    com.servlet.RegLet
  


  
    LogLet
    /LogLet
  
  
    RegLet
    /RegLet
  
  
  
  
  
  
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  

3.DBManager.java 链接数据库

package com.db;
 
import java.sql.*;
 
public class DBManager {
 
    // 数据库连接常量
    public static final String DRIVER = "com.mysql.jdbc.Driver";  
    public static final String USER = "root";     //用户名
    public static final String PASS = "123456";     //密码
    public static final String URL = "jdbc:mysql://localhost:3306/test";      //端口3306 数据库名test
 
    // 静态成员,支持单态模式
    private static DBManager per = null;
    private Connection conn = null;
    private Statement stmt = null;
 
    // 单态模式-懒汉模式
    private DBManager() {
    }
 
    public static DBManager createInstance() {
        if (per == null) {
            per = new DBManager();
            per.initDB();
        }
        return per;
    }
 
    // 加载驱动
    public void initDB() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 连接数据库,获取句柄+对象
    public void connectDB() {
        System.out.println("Connecting to database...");
        try {
            conn = DriverManager.getConnection(URL, USER, PASS);
            stmt = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("SqlManager:Connect to database successful.");
    }
 
    // 关闭数据库 关闭对象,释放句柄
    public void closeDB() {
        System.out.println("Close connection to database..");
        try {
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("Close connection successful");
    }
 
    // 查询
    public ResultSet executeQuery(String sql) {
        ResultSet rs = null;
        try {
            rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
 
    // 增添/删除/修改
    public int executeUpdate(String sql) {
        int ret = 0;
        try {
            ret = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ret;
    }
}

4.Service.java访问数据库功能实现数据库的增、查功能

package com.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.db.DBManager;

public class Service {

    public Boolean login(String username, String password) {

        // 获取Sql查询语句
        String logSql = "select * from user where username ='" + username
                + "' and password ='" + password + "'";

        // 获取DB对象
        DBManager sql = DBManager.createInstance();
        sql.connectDB();

        // 操作DB对象
        try {
            ResultSet rs = sql.executeQuery(logSql);
            if (rs.next()) {
                sql.closeDB();
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        sql.closeDB();
        return false;
    }

    public Boolean register(String username, String password) {
    
        // 获取Sql查询语句
        String regSql = "insert into user values('"+ username+ "','"+ password+ "') ";

        // 获取DB对象
        DBManager sql = DBManager.createInstance();
        sql.connectDB();

        int ret = sql.executeUpdate(regSql);
        if (ret != 0) {
            sql.closeDB();
            return true;
        }
        sql.closeDB();
        
        return false;
    }
}

5.LogLet.java 实现登陆功能的servlet

package com.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.service.Service;
 
public class LogLet extends HttpServlet{
 
	private static final long serialVersionUID = 9036889586892331384L;
 
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接受客户端信息
		String username = request.getParameter("username");
		username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
		String password = request.getParameter("password");
		password = new String(password.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println(username + ":" + password);
		
		//新建服务对象
		Service service = new Service();
		
		//验证处理
		boolean log = service.login(username, password);
		if( log ){
			System.out.println("log success");
			//request.getSession().setAttribute("username", username);
		}else{
			System.out.println("log fail");
		}
		
		//返回信息到客户端
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		if( log ){
			out.print("用户名:" + username);
			out.print("密码: " + password);
		}else{
			out.print("false");
		}
		out.flush();
		out.close();

		
	}
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
 
	}
 
}

6.RegLet.java 实现注册功能的servlet

package com.servlet;

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

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

import com.service.Service;

public class RegLet extends HttpServlet {
	private static final long serialVersionUID = 9036889586892331384L;
	 
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接受客户端信息
		String username = request.getParameter("username");
		username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
		String password = request.getParameter("password");
		password = new String(password.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println(username + ":" + password);
		
		//新建服务对象
		Service service = new Service();
		
		//验证处理
		boolean log = service.register(username, password);
		if( log ){
			System.out.println("log success");
			//request.getSession().setAttribute("username", username);
		}else{
			System.out.println("log fail");
		}
		
		//返回信息到客户端
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		if( log ){
			out.print("用户名:" + username);
			out.print("密码: " + password);
		}else{
			out.print("false");
		}
		out.flush();
		out.close();

		
	}
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
 
	}
 
}

到这里java web 端完成了
二、Mysql数据库
1.新建数据库test 数据库名test 与java web中的数据库名保持一致
2.建表 包含用户名username字段 和密码 password字段
sql语句

CREATE TABLE user(username VARCHAR(30) primary KEY,
PASSWORD VARCHAR(30) NOT NULL
);

这里数据库和web 服务器都完成了,然后运行web
双击index.jsp然后运行
1.再浏览器输入http://localhost:8080/HelloWeb/RegLet?username=aaa&password=123回车
如果显示

android HTTP 登陆链接Mysql数据库实现登陆_第2张图片

说明注册功能没问题

2.数据库新建查询 执行sql语句 SELECT * FROM user;

android HTTP 登陆链接Mysql数据库实现登陆_第3张图片

说明注册成功,并向数据库中插入数据成功

3.在浏览器中输入 http://localhost:8080/HelloWeb/LogLet?username=aaa&password=123回车
如果出现
android HTTP 登陆链接Mysql数据库实现登陆_第4张图片

说明登陆功能没问题

到这里服务端没问题并且可以成功运行了

三、Android端

1.工程目录 两个Activity Login登陆功能 Register注册功能
android HTTP 登陆链接Mysql数据库实现登陆_第5张图片

Login.java
注意:链接服务器web部分需要到线程中完成

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Login extends AppCompatActivity implements View.OnClickListener{

    private EditText username;
    private EditText password;
    private Button login;
    private TextView info;
    private TextView register;
    //提示框
    private ProgressDialog dialog;
    //服务器返回的数据
    private String infoString;

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

        //初始化信息
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        login = (Button)findViewById(R.id.btn_login);
        info = (TextView)findViewById(R.id.info);
        register = (TextView)findViewById(R.id.register);

        //设置按钮监听器
        login.setOnClickListener(this);
        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_login:
                //设置提示框


                //设置子线程,分别进行Get和Post传输数据
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            String path = "http://10.0.2.2:8080/HelloWeb/LogLet" + "?username=" + username.getText() + "&password=" + password.getText();
                            URL url = new URL(path);
                            URLConnection urlConnection = url.openConnection();
                            InputStream in = urlConnection.getInputStream();
                            printInputStream(in);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

                break;
            case R.id.register:
                //跳转注册页面
                Intent intent = new Intent(Login.this,Register.class);
                startActivity(intent);
                break;
        }
    }

    private void printInputStream(InputStream is){
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String rs = sb.toString();
        Log.e("登陆信息",rs);
    }



}

Register.java
注意:链接服务器web部分需要到线程中完成

import android.app.ProgressDialog;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Register extends AppCompatActivity implements View.OnClickListener{

    private EditText regUserName;
    private EditText regPassWord;
    private Button btn_reg;

    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //修改标题栏title
        ActionBar ac = getSupportActionBar();
        ac.setTitle("注册");

        //初始化
        regUserName = (EditText)findViewById(R.id.regUserName);
        regPassWord = (EditText)findViewById(R.id.regPassWord);
        btn_reg = (Button)findViewById(R.id.btn_reg);

        btn_reg.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_reg:
               

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            String path = "http://10.0.2.2:8080/HelloWeb/RegLet" + "?username=" + regUserName.getText() + "&password=" + regPassWord.getText();
                            URL url = new URL(path);
                            URLConnection urlConnection = url.openConnection();
                            InputStream in = urlConnection.getInputStream();
                            printInputStream(in);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
        }
    }

    private void printInputStream(InputStream is){
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String rs = sb.toString();
        Log.e("注册信息",rs);
    }

}

布局文件很简单 这里不给出登陆注册

android HTTP 登陆链接Mysql数据库实现登陆_第6张图片android HTTP 登陆链接Mysql数据库实现登陆_第7张图片

2.AndroidManifest.xml(重点)****
添加网络权限

主界面设为Login.java

        
            

            
        
    

在application中添加 android:usesCleartextTraffic=“true”(重点)

整个AndroidManifest.xml




    

    

        

            
                

                
            
        
        
    


好了android程序写完了,运行
android HTTP 登陆链接Mysql数据库实现登陆_第8张图片
android HTTP 登陆链接Mysql数据库实现登陆_第9张图片

到这里就结束了****实现了android模拟器链接web服务器再链接数据库

但是这里只是实现模拟器链接,如果需要真机链接pc web端服务器就需要内网穿透
(是公网ip请绕过)

四、实现真机访问pc服务器,实现注册、登陆功能
1.很多提供内网穿透服务,这里我们选择花生壳内网穿透

android HTTP 登陆链接Mysql数据库实现登陆_第10张图片

选择新增映射
android HTTP 登陆链接Mysql数据库实现登陆_第11张图片

内网主机填ip地址 控制台 ipconfig/all查看端口号填谢web服务器的端口
android HTTP 登陆链接Mysql数据库实现登陆_第12张图片

确定android HTTP 登陆链接Mysql数据库实现登陆_第13张图片

将外网访问部分复制到android程序
android HTTP 登陆链接Mysql数据库实现登陆_第14张图片
替换掉里面的10.0.2.2:8080这样

无论哪里的手机,接入什么样的网络都可以链接你PC的web服务器了

最后运行android程序

**源码:**链接:https://pan.baidu.com/s/1RbCKBo7RHxCABOgckmx0Ng
提取码:h7rz

总结:mysql新建数据库,建立web服务器
android端通过http访问PC 机web服务器
重点## 在application中添加 android:usesCleartextTraffic=“true”(重点)
添加网络权限

你可能感兴趣的:(android)