Android Studio+Servlet+MySql實(shí)現(xiàn)登錄注冊(cè)
一、Android 項(xiàng)目當(dāng)中設(shè)置明文傳輸
1、設(shè)置明文傳輸?shù)膞ml




<?xml version="1.0" encoding="UTF-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
2、引入上述創(chuàng)建的xml

android:networkSecurityConfig="@xml/network_security_config"
二、在MyEclipse當(dāng)中創(chuàng)建Web項(xiàng)目
1、創(chuàng)建項(xiàng)目

引入MySQL的驅(qū)動(dòng)包

2、創(chuàng)建實(shí)體類(lèi)User

package entity;
public class User {
private int id;
private String name;
private String username;
private String password;
private int age;
private String phone;
public User() {
}
public User(int id, String name, String username, String password, int age, String phone) {
this.id = id;
this.name = name;
this.username = username;
this.password = password;
this.age = age;
this.phone = phone;
}
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 getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
3、創(chuàng)建JDBCUtils工具類(lèi)

package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtils {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
Connection conn = null;
try {
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
}catch (Exception exception){
exception.printStackTrace();
}
return conn;
}
public static void close(Connection conn){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
4、創(chuàng)建UserDao類(lèi)

package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import entity.User;
public class UserDao {
public boolean login(String name,String password){
String sql = "select * from users where name = ? and password = ?";
Connection con = JDBCUtils.getConn();
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,name);
pst.setString(2,password);
if(pst.executeQuery().next()){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return false;
}
public boolean register(User user){
String sql = "insert into users(name,username,password,age,phone) values (?,?,?,?,?)";
Connection con = JDBCUtils.getConn();
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,user.getName());
pst.setString(2,user.getUsername());
pst.setString(3,user.getPassword());
pst.setInt(4,user.getAge());
pst.setString(5,user.getPhone());
int value = pst.executeUpdate();
if(value>0){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return false;
}
public User findUser(String name){
String sql = "select * from users where name = ?";
Connection con = JDBCUtils.getConn();
User user = null;
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,name);
ResultSet rs = pst.executeQuery();
while (rs.next()){
int id = rs.getInt(1);
String namedb = rs.getString(2);
String username = rs.getString(3);
String passworddb = rs.getString(4);
int age = rs.getInt(5);
String phone = rs.getString(6);
user = new User(id,namedb,username,passworddb,age,phone);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return user;
}
}
5、創(chuàng)建對(duì)應(yīng)的LoginServlet




package 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 dao.UserDao;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
UserDao dao = new UserDao();
boolean login = dao.login(name, password);
String msg = "";
if(login){
msg = "成功";
}else{
msg = "失敗";
}
PrintWriter out = response.getWriter();
out.println(msg);
out.flush();
out.close();
}
}
三、在Android Studio當(dāng)中調(diào)用Servlet
(一)實(shí)現(xiàn)登錄功能
1、創(chuàng)建連接Servlet的工具類(lèi)(PostUtil)


package com.example.application01.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
//訪(fǎng)問(wèn)servlet
public class PostUtil {
//訪(fǎng)問(wèn)的serlver不一樣
//傳遞的參數(shù)不一樣
public static String Post(String url,String data)
{
String msg = "";
try{
//http://ms-yffprtappszi:8080/AndroidWeb/LoginServlet
HttpURLConnection conn = (HttpURLConnection) new URL("http://10.0.2.2:8080/AndroidWeb/"+url).openConnection();
//設(shè)置請(qǐng)求方式,請(qǐng)求超時(shí)信息
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//設(shè)置運(yùn)行輸入,輸出:
conn.setDoOutput(true);
conn.setDoInput(true);
//Post方式不能緩存,需手動(dòng)設(shè)置為false
conn.setUseCaches(false);
//我們請(qǐng)求的數(shù)據(jù):
//獲取輸出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
if (conn.getResponseCode() == 200) {
// 獲取響應(yīng)的輸入流對(duì)象
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line=null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
msg=response.toString();
}
}catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
}
2、在MainActivity調(diào)用這個(gè)類(lèi)

package com.example.application01;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.application01.dao.UserDao;
import com.example.application01.utils.PostUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void reg(View view){
startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
}
public void login(View view){
EditText EditTextname = (EditText)findViewById(R.id.name);
EditText EditTextpassword = (EditText)findViewById(R.id.password);
new Thread(){
@Override
public void run() {
String data="";
try {
data = "name="+ URLEncoder.encode(EditTextname.getText().toString(), "UTF-8")+
"&password="+ URLEncoder.encode(EditTextpassword.getText().toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String request = PostUtil.Post("LoginServlet",data);
int msg = 0;
if(request.equals("成功")){
msg = 1;
}
hand1.sendEmptyMessage(msg);
}
}.start();
}
final Handler hand1 = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == 1)
{
Toast.makeText(getApplicationContext(),"登錄成功",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"登錄失敗",Toast.LENGTH_LONG).show();
}
}
};
}
在開(kāi)啟web項(xiàng)目的情況下運(yùn)行Android項(xiàng)目

(二)實(shí)現(xiàn)注冊(cè)功能
1、在web工程當(dāng)中創(chuàng)建RegisterServlet




package 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 dao.UserDao;
import entity.User;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("-----------------");
response.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String phone = request.getParameter("phone");
int age = Integer.parseInt(request.getParameter("age"));
User user = new User();
user.setName(name);
user.setUsername(username);
user.setPassword(password);
user.setAge(age);
user.setPhone(phone);
String msg = "";
UserDao userDao = null;
User uu = null;
userDao = new UserDao();
uu = userDao.findUser(user.getName());
boolean flag = false;
if(uu == null){
flag = userDao.register(user);
}
if(flag){
msg = "成功";
}else{
msg = "失敗";
}
if(uu != null)
{
msg = "已存在";
}
PrintWriter out = response.getWriter();
out.println(msg);
out.flush();
out.close();
}
}
2、在Android當(dāng)中的RegisterActivity訪(fǎng)問(wèn)Servlet

package com.example.application01;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.application01.dao.UserDao;
import com.example.application01.entity.User;
import com.example.application01.utils.PostUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class RegisterActivity extends AppCompatActivity {
EditText name = null;
EditText username = null;
EditText password = null;
EditText phone = null;
EditText age = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
name = findViewById(R.id.name);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
phone = findViewById(R.id.phone);
age = findViewById(R.id.age);
}
public void register(View view){
String cname = name.getText().toString();
String cusername = username.getText().toString();
String cpassword = password.getText().toString();
System.out.println(phone.getText().toString());
String cphone = phone.getText().toString();
int cgae = Integer.parseInt(age.getText().toString());
if(cname.length() < 2 || cusername.length() < 2 || cpassword.length() < 2 ){
Toast.makeText(getApplicationContext(),"輸入信息不符合要求請(qǐng)重新輸入",Toast.LENGTH_LONG).show();
return;
}
User user = new User();
user.setName(cname);
user.setUsername(cusername);
user.setPassword(cpassword);
user.setAge(cgae);
user.setPhone(cphone);
new Thread(){
@Override
public void run() {
String data="";
try {
data = "&name="+ URLEncoder.encode(user.getName(), "UTF-8")+
"&username="+ URLEncoder.encode(user.getUsername(), "UTF-8")+
"&password="+ URLEncoder.encode(user.getPassword(), "UTF-8")+
"&age="+ URLEncoder.encode(user.getAge()+"", "UTF-8")+
"&phone="+ URLEncoder.encode(user.getPhone(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String request = PostUtil.Post("RegisterServlet",data);
int msg = 0;
if(request.equals("成功")){
msg = 2;
}
//已存在
if(request.equals("已存在")){
msg = 1;
}
hand.sendEmptyMessage(msg);
}
}.start();
}
final Handler hand = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == 0)
{
Toast.makeText(getApplicationContext(),"注冊(cè)失敗",Toast.LENGTH_LONG).show();
}
if(msg.what == 1)
{
Toast.makeText(getApplicationContext(),"該賬號(hào)已經(jīng)存在,請(qǐng)換一個(gè)賬號(hào)",Toast.LENGTH_LONG).show();
}
if(msg.what == 2)
{
//startActivity(new Intent(getApplication(),MainActivity.class));
Intent intent = new Intent();
//將想要傳遞的數(shù)據(jù)用putExtra封裝在intent中
intent.putExtra("a","註冊(cè)");
setResult(RESULT_CANCELED,intent);
finish();
}
}
};
}

到此這篇關(guān)于Android Studio+Servlet+MySql實(shí)現(xiàn)登錄注冊(cè) 的文章就介紹到這了,更多相關(guān)Android Studio 登錄注冊(cè) 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android Studio連接SQLite數(shù)據(jù)庫(kù)的登錄注冊(cè)實(shí)現(xiàn)
- Android Studio連接MySql實(shí)現(xiàn)登錄注冊(cè)(附源代碼)
- Android Studio實(shí)現(xiàn)注冊(cè)頁(yè)面跳轉(zhuǎn)登錄頁(yè)面的創(chuàng)建
- Android?studio?利用共享存儲(chǔ)進(jìn)行用戶(hù)的注冊(cè)和登錄驗(yàn)證功能
- Android Studio實(shí)現(xiàn)QQ的注冊(cè)登錄和好友列表跳轉(zhuǎn)
- Android?Studio中使用SQLite數(shù)據(jù)庫(kù)實(shí)現(xiàn)登錄和注冊(cè)功能
相關(guān)文章
Android 圓角 ImageView類(lèi)可設(shè)置弧度(代碼簡(jiǎn)單)
這篇文章主要介紹了Android 圓角 ImageView類(lèi)可設(shè)置弧度 的相關(guān)資料,需要的朋友可以參考下2016-03-03
Android中的SQLite數(shù)據(jù)庫(kù)簡(jiǎn)介
SQLite是Android系統(tǒng)采用的一種開(kāi)源的輕量級(jí)的關(guān)系型的數(shù)據(jù)庫(kù)。這篇文章主要介紹了Android中的SQLite數(shù)據(jù)庫(kù)簡(jiǎn)介,需要的朋友可以參考下2017-03-03
Android自定義動(dòng)態(tài)壁紙開(kāi)發(fā)詳解
這篇文章主要為大家詳細(xì)介紹了Android自定義動(dòng)態(tài)壁紙開(kāi)發(fā),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
Android進(jìn)階NestedScroll嵌套滑動(dòng)機(jī)制實(shí)現(xiàn)吸頂效果詳解
這篇文章主要為大家介紹了Android進(jìn)階NestedScroll嵌套滑動(dòng)機(jī)制實(shí)現(xiàn)吸頂效果詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Android 獲取正在運(yùn)行的任務(wù)和服務(wù)的小例子
Android 獲取正在運(yùn)行的任務(wù)和服務(wù)的小例子,需要的朋友可以參考一下2013-05-05

