Android开发入门案例

  • 时间:
  • 浏览:9
  • 来源:跟我学网络

初次接触安卓,做出来一个还能看的案例,类似小说阅读的APP,将源码记录一下

一、案例效果

1.登录界面

2.注册界面

3.用户信息显示界面

4.小说阅读界面

二、安卓代码

1.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mychat">
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <!--过滤器规定的是首先展示的Activity-->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".activities.SuccessActivity"></activity>
        <activity android:name=".activities.RegisterActivity"></activity>
        <activity android:name=".activities.ReadingActivity"></activity>

    </application>

</manifest>

2. 布局

2.1activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:clickable="true"
    tools:context="com.example.mychat.activities.LoginActivity">

    <EditText
        android:id="@+id/et_login_uname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名:" />

    <EditText
        android:id="@+id/et_data_upass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码:"
        android:inputType="number"/>

    <TextView
        android:id="@+id/msg_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btn_login"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="loginPOST"
        android:background="@color/colorMine"
        android:text="点击登陆" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_register"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorMine"
        android:onClick="doReg"
        android:text="点击注册" />
</LinearLayout>
2.2activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/et_data_uname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名:" />

    <EditText
        android:id="@+id/et_data_upass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码:"
        android:inputType="number"/>

    <EditText
        android:id="@+id/et_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入年龄:" />

    <EditText
        android:id="@+id/et_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入性别:" />

    <EditText
        android:id="@+id/et_reading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入正在阅读的小说,使用封号隔开:" />

    <EditText
        android:id="@+id/et_favorite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入喜欢的小说类型" />

    <TextView
        android:id="@+id/msg_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <!--<Button
        android:id="@+id/btn_login"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="toLogin"
        android:background="@color/colorMine"
        android:text="去登陆页面" />-->

    <ImageView
        android:id="@+id/image01"
        android:layout_width="505dp"
        android:layout_height="206dp"
        android:layout_gravity="center"
        android:src="@mipmap/bbb" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_register"
        android:layout_width="490dp"
        android:layout_height="31dp"
        android:layout_gravity="center"
        android:background="@color/colorMine"
        android:onClick="registerPOST"
        android:text="点击注册" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_login"
        android:layout_width="491dp"
        android:layout_height="37dp"
        android:layout_gravity="center"
        android:background="@color/colorMine"
        android:onClick="toLogin"
        android:text="去登陆页面" />


</LinearLayout>
2.3activity_success.xml
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/wel"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="尊敬的用户,欢迎您回来,您的信息如下:"
        android:gravity="center"
        android:background="@color/colorMine2"/>

    <TextView
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="姓名:朱有财"
        android:gravity="left"
        android:background="@color/colorMine"/>

    <TextView
        android:id="@+id/user_gender"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="性别:女"
        android:gravity="left"
        android:background="@color/colorMine"/>
    <TextView
        android:id="@+id/user_age"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="芳龄:18"
        android:gravity="left"
        android:background="@color/colorMine"/>

    <TextView
        android:id="@+id/user_interests"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="兴趣爱好:玄幻,科技,穿越,重生"
        android:gravity="left"
        android:background="@color/colorMine"/>

    <TextView
        android:id="@+id/user_read"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="已经阅读书籍: 甄嬛传,三体"
        android:gravity="left"
        android:background="@color/colorMine"/>

    <!--<ImageView
        android:id="@+id/image01"
        android:layout_width="505dp"
        android:layout_height="339dp"
        android:layout_gravity="left"
        android:src="@mipmap/bbb" />-->

    <TextView
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:text="您最近在读的作品:"
        android:gravity="center"
        android:background="@color/colorMine3"/>

    <TextView
        android:id="@+id/reading1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text=""
        android:gravity="center"
        android:clickable="true"
        android:background="@color/colorMine4"/>
    <TextView
        android:id="@+id/reading2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text=""
        android:gravity="center"
        android:clickable="true"
        android:background="@color/colorMine4"/>
    <TextView
        android:id="@+id/reading3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text=""
        android:gravity="center"
        android:clickable="true"
        android:background="@color/colorMine4"/>

<!--
    <Button
        android:id="@+id/btn_query01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="queryStories"
        android:background="@color/colorMine4"
        android:text="" />

    <Button
        android:id="@+id/btn_query02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="queryStories"
        android:background="@color/colorMine4"
        android:text="" />

    <Button
        android:id="@+id/btn_query03"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="queryStories"
        android:background="@color/colorMine4"
        android:text="" />

    <Button
        android:id="@+id/btn_query04"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="queryStories"
        android:background="@color/colorMine4"
        android:text="" />

    <Button
        android:id="@+id/btn_query05"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="queryStories"
        android:background="@color/colorMine4"
        android:text="" />-->
</LinearLayout>
2.4activity_reading.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/context_roll"
        android:layout_width="fill_parent"
        android:layout_height="720dp"
        android:background="@color/colorMine5"
        android:scrollbarStyle="outsideOverlay">

        <TextView
            android:id="@+id/context"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:textColor="@color/colorMine6"
            android:textSize="26sp"/>

    </ScrollView>



</LinearLayout>

3 Activities

3.1 LoginActivity
package com.example.mychat.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mychat.R;
import com.example.mychat.utils.PostUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

    String TAG = LoginActivity.class.getCanonicalName();
    private EditText et_login_uname;
    private EditText et_data_upass;
    private TextView msg_show;
    private Button btn_register;
    private HashMap<String, String> stringHashMap;
    private static final int COMPLETED=0;
    String msg_toShow="";

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what==COMPLETED){
                msg_show.setText(msg_toShow);
            }
        }
    };


    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        et_login_uname = (EditText) findViewById(R.id.et_login_uname);
        et_data_upass = (EditText) findViewById(R.id.et_data_upass);
        msg_show=(TextView)findViewById(R.id.msg_show);
        btn_register=(Button)findViewById(R.id.btn_register);
        stringHashMap = new HashMap<>();
    }

    public String username;

    public void loginPOST(View view) {
        username=et_login_uname.getText().toString();
        stringHashMap.put("username",username);
        stringHashMap.put("password", et_data_upass.getText().toString());
        new Thread(postRun).start();
    }



    
    Runnable postRun = new Runnable() {
        PostUtils postUtils=new PostUtils();
        int flag;
        String msg;
        @Override
        public void run() {
            
            try {
                String loginUrl="http://192.168.10.108:8080/MyChat/LoginServlet";
                String result=postUtils.requestPost(loginUrl,stringHashMap);
                JSONObject jsonObject =new JSONObject(result);
                flag=jsonObject.getInt("code");
                msg_toShow=jsonObject.getString("msg");
                if(flag!=1){
                    
                    
                    
                    Message message=new Message();
                    message.what=COMPLETED;
                    handler.sendMessage(message);
                }else{
                    
                    
                    Intent intent=new Intent(LoginActivity.this, SuccessActivity.class);
                    

                    
                    String queryByUsernameUrl="http://192.168.10.108:8080/MyChat/QueryServlet";
                    HashMap stringHashMap=new HashMap<String,String>();
                    stringHashMap.put("queryByUsernameUrl",queryByUsernameUrl);
                    stringHashMap.put("username",username);
                    String user_info=postUtils.requestPost(queryByUsernameUrl,stringHashMap);


                    JSONObject jsonObject_userInfo = null;
                    jsonObject_userInfo = new JSONObject(user_info);
                    
                    flag=jsonObject_userInfo.getInt("code");
                    JSONObject jsonObject1 = jsonObject_userInfo.getJSONObject("data");
                            
                    
                    String password=jsonObject1.optString("password");
                    String gender=jsonObject1.optString("gender");
                    String age=jsonObject1.optString("age");
                    String favorite=jsonObject1.optString("favorite");
                    String reading=jsonObject1.optString("reading");

                    
                    System.out.println("当前用户的喜好是"+favorite);
                    
                    Bundle bundle=new Bundle();
                    ArrayList<String> list=new ArrayList<String>();
                    list.add(username);
                    list.add(password);
                    list.add(gender);
                    list.add(age);
                    list.add(favorite);
                    list.add(reading);

                    bundle.putStringArrayList("user",list);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    
    
    public void doReg(View view){
        Intent intent=new Intent(this,RegisterActivity.class);
        startActivity(intent);
    }
}
3.2 RegisterActivity
package com.example.mychat.activities;

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.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mychat.R;
import com.example.mychat.utils.PostUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


public class RegisterActivity extends AppCompatActivity {

    String TAG = RegisterActivity.class.getCanonicalName();
    private EditText et_data_uname,et_data_upass,et_gender,et_age,et_favorite,et_reading;
    private TextView msg_show;
    private HashMap<String, String> stringHashMap;

    private static final int COMPLETED=0;
    
    String msg_toShow="";


    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        et_data_uname = (EditText) findViewById(R.id.et_data_uname);
        et_data_upass = (EditText) findViewById(R.id.et_data_upass);
        et_age= (EditText) findViewById(R.id.et_age);
        et_gender = (EditText) findViewById(R.id.et_gender);
        et_favorite = (EditText) findViewById(R.id.et_favorite);
        et_reading = (EditText) findViewById(R.id.et_reading);
        msg_show=(TextView)findViewById(R.id.msg_show);
        stringHashMap = new HashMap<>();
    }


    public void registerPOST(View view) {
        stringHashMap.put("username", et_data_uname.getText().toString());
        stringHashMap.put("password", et_data_upass.getText().toString());
        stringHashMap.put("age", et_age.getText().toString());
        stringHashMap.put("gender", et_gender.getText().toString());
        stringHashMap.put("favorite", et_favorite.getText().toString());
        stringHashMap.put("reading", et_reading.getText().toString());
        new Thread(postRun).start();
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what==COMPLETED){
                msg_show.setText(msg_toShow);
            }
        }
    };



    
    Runnable postRun = new Runnable() {
        PostUtils postUtils=new PostUtils();
        int flag;
        String msg;
        @Override
        public void run() {
            
            try {
                
                String registerUrl="http://192.168.10.108:8080/MyChat/RegisterServlet";
                String result=postUtils.requestPost(registerUrl,stringHashMap);
                JSONObject jsonObject = new JSONObject(result);
                flag=jsonObject.getInt("code");
                msg_toShow=jsonObject.getString("msg");
                if(flag!=1){
                    
                    Message message=new Message();
                    message.what=COMPLETED;
                    handler.sendMessage(message);
                }else{
                    
                    Message message=new Message();
                    message.what=COMPLETED;
                    handler.sendMessage(message);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    };

    
    
    public void toLogin(View view){
        Intent intent=new Intent(this,LoginActivity.class);
        startActivity(intent);
    }


}
3.3ReadingActivity
package com.example.mychat.activities;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mychat.R;

public class ReadingActivity extends AppCompatActivity {

    TextView tv_context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reading);
        Bundle bundle = this.getIntent().getExtras();
        String context = bundle.getString("context");

        tv_context = (TextView) findViewById(R.id.context);
        tv_context.setText(context);

    }
}
3.4 SuccessActivity
package com.example.mychat.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mychat.R;
import com.example.mychat.utils.PostUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class SuccessActivity extends AppCompatActivity implements View.OnClickListener {
    
    TextView welText ,user_name,user_age,user_gender,user_interests;
    TextView reading1,reading2,reading3;
    
    String reading;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_success);

        
        Bundle bundle = this.getIntent().getExtras();
        ArrayList<String> user = bundle.getStringArrayList("user");
        String username=user.get(0);
        String password=user.get(1);
        String gender=user.get(2);
        String age=user.get(3);
        String favorite=user.get(4);
        String reading=user.get(5);
        String[] readings = reading.split(";");


        welText = (TextView) findViewById(R.id.wel);
        user_name = (TextView) findViewById(R.id.user_name);
        user_age=(TextView)findViewById(R.id.user_age);
        user_gender=(TextView)findViewById(R.id.user_gender);
        user_interests=(TextView)findViewById(R.id.user_interests);
        reading1 = (TextView) findViewById(R.id.reading1);
        reading2 = (TextView) findViewById(R.id.reading2);
        reading3 = (TextView) findViewById(R.id.reading3);
        reading1.setOnClickListener(this);
        reading2.setOnClickListener(this);
        reading3.setOnClickListener(this);
        
        
        
        

        
        user_name.setText("用户名称: "+username);
        user_age.setText("用户年龄: "+age);
        user_gender.setText("用户性别: "+gender);
        user_interests.setText("喜爱的小说类型: "+favorite);
        reading1.setText(readings[0]);
        reading2.setText(readings[1]);
        reading3.setText(readings[2]);

    }

    final String queryByBooknameUrl = "http://192.168.10.108:8080/MyChat/reading";
    final HashMap stringHashMap = new HashMap<String, String>();
    
    @Override
    public void onClick(View view) {

        
        
        
        switch (view.getId()) {
            case R.id.reading1:
                stringHashMap.put("reading", reading1.getText().toString());
                break;
            case R.id.reading2:
                stringHashMap.put("reading", reading2.getText().toString());
                break;
            case R.id.reading3:
                stringHashMap.put("reading", reading3.getText().toString());
                break;
        }
        new Thread(postRun).start();

    }
        
        Runnable postRun = new Runnable() {
            PostUtils postUtils=new PostUtils();
            String context = null;
            String bookName=null;
            @Override
            public void run() {
                String result = postUtils.requestPost(queryByBooknameUrl, stringHashMap);

                if (result == null) {
                    System.out.println("当前小说不能阅读");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        

                        JSONObject jsonObject_data = jsonObject.getJSONObject("data");
                        bookName=jsonObject_data.getString("bookName");
                        context=jsonObject_data.getString("context");
                        Intent intent=new Intent(SuccessActivity.this,ReadingActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putString("context",context);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

    }

三、后端代码(使用Idea开发)

需要加入gson和mysql连接的jar包

3.1 servlet

3.1.1 LoginDateServlet
package com.south.web;

import com.google.gson.Gson;
import com.south.domain.BaseBean;
import com.south.domain.UserBean;
import com.south.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LoginDateServlet extends HttpServlet {

	

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").format(new Date()));
		System.out.println("成功连接到安卓服务器");
		request.setCharacterEncoding("UTF-8");
		System.out.println("request--->"+request.getRequestURL()+"===="+request.getParameterMap().toString());
		String username = request.getParameter("username"); 
		String password = request.getParameter("password");
		response.setContentType("text/html;charset=utf-8");
		if (username == null || username.equals("") || password == null || password.equals("")) {
			System.out.println("用户名或密码为空");
			return;
		} 
		DBUtils dbUtils = new DBUtils();
		dbUtils.openConnect();
		
		BaseBean data = new BaseBean(); 
		UserBean userBean = new UserBean(); 
		if (dbUtils.isExistInDB(username, password)) {
			
			data.setCode(1);
			data.setData(userBean);
			data.setMsg("登陆成功");
		} else if (!dbUtils.isExistInDB(username, password)) {
			
			data.setCode(0);
			data.setMsg("用户名或密码错误!!");
			System.out.println("用户名或密码错误");
		}
		Gson gson = new Gson();
		String json = gson.toJson(data);
		System.out.println("转换GSON成功,要传送给客户端的数据是"+json);
		
		try {
			response.getWriter().println(json);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			response.getWriter().close(); 
		}
		dbUtils.closeConnect(); 
	}
	

}
3.1.2 RegisterServlet
package com.south.web;

import com.google.gson.Gson;
import com.south.domain.BaseBean;
import com.south.domain.UserBean;
import com.south.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RegisterServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").format(new Date()));
        System.out.println("成功连接到安卓服务器");
        request.setCharacterEncoding("UTF-8");
        System.out.println("request--->"+request.getRequestURL()+"===="+request.getParameterMap().toString());
        String username = request.getParameter("username"); 
        String password = request.getParameter("password");
        String age = request.getParameter("age");
        String gender = request.getParameter("gender");
        String favorite = request.getParameter("favorite");
        String reading = request.getParameter("reading");

        response.setContentType("text/html;charset=utf-8");

        
        if (username == null || username.equals("") || password == null || password.equals("")) {
            System.out.println("用户名或密码为空");
            return;
        } 
        DBUtils dbUtils = new DBUtils();
        dbUtils.openConnect();
        
        BaseBean data = new BaseBean(); 
        UserBean userBean = new UserBean(); 
        if (dbUtils.isExistInDB(username, password)) {
            
            data.setCode(0);
            data.setData(userBean);
            data.setMsg("该账号已存在,请重新填写用户名称");
            System.out.println("账号已经存在!!");
        } else if (!dbUtils.insertDataToDB(username, password,age,gender,favorite,reading)) {
            
            data.setCode(0);
            data.setMsg("注册成功!!请点击登陆按钮进行登陆");
            System.out.println("注册成功,请点击登陆按钮进行登陆");
            ResultSet rs = dbUtils.getUser();
            int id = -1;
            
            if (rs != null) {
                try {
                    while (rs.next()) {
                        if (rs.getString("user_name").equals(username)&& rs.getString("user_pwd").equals(password)) {
                            id = rs.getInt("user_id");
                        }
                    }
                    userBean.setId(id);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            userBean.setUsername(username);
            userBean.setPassword(password);
            userBean.setAge(age);
            userBean.setGender(gender);
            userBean.setReading(reading);
            userBean.setFavorite(favorite);
            data.setData(userBean);
        } else {
            
            data.setCode(500);
            data.setData(userBean);
            data.setMsg("数据库错误");
        }
        Gson gson = new Gson();
        String json = gson.toJson(data);
        System.out.println("转换GSON成功,要传送给客户端的数据是"+json);
        
        try {
            response.getWriter().println(json);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getWriter().close(); 
        }
        dbUtils.closeConnect(); 
    }
}
3.1.3 QueryServlet
package com.south.web;

import com.google.gson.Gson;
import com.south.domain.BaseBean;
import com.south.domain.UserBean;
import com.south.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class QueryServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println(new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").format(new Date()));
        System.out.println("成功连接到安卓服务器");
        request.setCharacterEncoding("UTF-8");
        System.out.println("request--->"+request.getRequestURL()+"===="+request.getParameterMap().toString());
        String username = request.getParameter("username"); 
        response.setContentType("text/html;charset=utf-8");

        
        if (username == null || username.equals("")) {
            System.out.println("用户名为空");
            return;
        } 
        DBUtils dbUtils = new DBUtils();
        dbUtils.openConnect();
        
        BaseBean data = new BaseBean(); 
        UserBean userBean = new UserBean(); 
        ResultSet rs=dbUtils.queryByUsername(username);

        
        if (rs != null) {
                while (true) {
                    try {
                        if (!rs.next()) break;
                        userBean.setUsername(rs.getString("user_name"));
                        userBean.setPassword(rs.getString("user_pwd"));
                        userBean.setGender(rs.getString("user_gender"));
                        userBean.setAge(rs.getString("user_age"));
                        userBean.setFavorite(rs.getString("user_favorite"));
                        userBean.setReading(rs.getString("user_reading"));

                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                    }
                }
            data.setData(userBean);

        Gson gson = new Gson();
        String json = gson.toJson(data);
        System.out.println("转换GSON成功,要传送给客户端的数据是"+json);
        
        try {
            response.getWriter().println(json);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getWriter().close(); 
        }
        dbUtils.closeConnect(); 
    }
}
3.1.4 QueryReadingServlet
package com.south.web;

import com.google.gson.Gson;
import com.south.domain.BaseBean;
import com.south.domain.BookBean;
import com.south.domain.UserBean;
import com.south.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class QueryReadingServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println(new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").format(new Date()));
        System.out.println("成功连接到安卓服务器");
        request.setCharacterEncoding("UTF-8");
        System.out.println("request--->"+request.getRequestURL()+"===="+request.getParameterMap().toString());
        String reading = request.getParameter("reading"); 
        response.setContentType("text/html;charset=utf-8");

        BaseBean data=new BaseBean();
        BookBean bookBean = new BookBean();

        DBUtils dbUtils = new DBUtils();
        dbUtils.openConnect();
        
        ResultSet rs=dbUtils.queryContextByName(reading);
        String bookName=null;
        String context=null;
        

        if (rs != null) {
            while (true) {
                try {
                    if (!rs.next()) break;
                    bookName=rs.getString("book_name");
                    context= rs.getString("context");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }

        
        bookBean.setContext(context);
        bookBean.setBookName(bookName);
        data.setCode(0);
        data.setMsg("请求小说内容成功");
        data.setData(bookBean);

        Gson gson = new Gson();
        String json = gson.toJson(data);
        System.out.println("转换GSON成功,要传送给客户端的数据是"+json);
        
        try {
            response.getWriter().println(json);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getWriter().close(); 
        }
        dbUtils.closeConnect(); 
    }
}

3.2 utils

package com.south.utils;

import com.south.domain.UserBean;

import java.sql.*;

public class DBUtils {
	private Connection conn;
	private String url = "jdbc:mysql://127.0.0.1:3306/mychat"; 
	private String user = "root"; 
	private String password = "root"; 
	private Statement sta;
	private ResultSet rs; 


	public void openConnect() {
		try {
			
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			if (conn != null) {
				System.out.println("数据库连接成功"); 
			}
		} catch (Exception e) {
			System.out.println("ERROR: " + e.getMessage());
		}
	}


	
	public ResultSet getUser() {
		
		try {
			sta = conn.createStatement(); 
			rs = sta.executeQuery("select * from user");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}


	
	public boolean isExistInDB(String username, String password) {
		boolean isFlag = false; 
		try {
			System.out.println("判断用户名密码");
			sta = conn.createStatement(); 
			rs = sta.executeQuery("select * from user");
			if (rs != null) {
				while (rs.next()) { 
					if (rs.getString("user_name").equals(username)) {
						if (rs.getString("user_pwd").equals(password)) {
							isFlag = true;
							break;
						}
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			isFlag = false;
		}
		return isFlag;


	}

	
	public boolean insertDataToDB(String username, String password,String age,String gender,String favorite,String reading) {

		String sql = " insert into user (user_name,user_pwd,user_gender,user_age,user_favorite,user_reading)values (?,?,?,?,?,?)";
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1,username);
			ps.setString(2,password);
			ps.setString(3,age);
			ps.setString(4,gender);
			ps.setString(5,favorite);
			ps.setString(6,reading);
			
			return ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	
	public ResultSet queryByUsername(String username){
		
		
		String sql="select * from user where user_name = ? ";
		try {
			PreparedStatement st = conn.prepareStatement(sql);
			st.setString(1,username);
			rs=st.executeQuery();
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public void closeConnect() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (sta != null) {
				sta.close();
			}
			if (conn != null) {
				conn.close();
			}
			System.out.println("关闭数据库连接成功");
		} catch (SQLException e) {
			System.out.println("Error: " + e.getMessage());
		}
	}


	public ResultSet queryContextByName(String bookName) {
		String sql="select * from book_reading where book_name = ? ";
		try {
			PreparedStatement st = conn.prepareStatement(sql);
			st.setString(1,bookName);
			rs=st.executeQuery();
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

3.3 beans

3.3.1BaseBean
package com.south.domain;

public class BaseBean {
	private int code;
	private String msg;
	private Object data;


	public int getCode() {
		return code;
	}


	public void setCode(int code) {
		this.code = code;
	}


	public String getMsg() {
		return msg;
	}


	public void setMsg(String msg) {
		this.msg = msg;
	}


	public Object getData() {
		return data;
	}


	public void setData(Object data) {
		this.data = data;
	}

}

3.3.2UserBean
package com.south.domain;

import java.io.Serializable;

public class UserBean implements Serializable {
	
	private int id;
	private String username;
	private String password;
	private String gender;
	private String age;
	private String favorite;
	private String reading;

	public String getReading() {
		return reading;
	}

	public void setReading(String reading) {
		this.reading = reading;
	}

	public UserBean(int id, String username, String password, String gender, String age, String favorite,String reading) {
		this.id = id;
		this.username = username;
		this.password = password;
		this.gender = gender;
		this.age = age;
		this.favorite = favorite;
		this.reading=reading;
	}

	public UserBean() {
	}

	public int getId() {
		return id;
	}

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

	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 String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getFavorite() {
		return favorite;
	}

	public void setFavorite(String favorite) {
		this.favorite = favorite;
	}
}
3.3.3BookBean
package com.south.domain;

public class BookBean {
    private String bookName;
    private String context;

    public BookBean() {
    }

    public BookBean(String bookName, String context) {
        this.bookName = bookName;
        this.context = context;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }
}

总结

参考博客[https://www.jb51.net/article/86984.htm(https://www.jb51.net/article/86984.htm),第一次做安卓开发,前后端都要写,时间也比较短,很多地方没有优化,该判断的地方也没有判断,需要try,catch 的地方也没有继续做,好几处变量的声明与定义都没有规范,如果有小伙伴要运行代码的话主要注意注册界面由于没有判断所以需要输入三个书名,也就是有两个;;才能保证登陆的时候不会报错,因为没有做变量的优化

前端项目已经上传到百度云 链接:https://pan.baidu.com/s/1p_wXO5Uwqn1mluXIuJGWyw 提取码: 9cds,后端由于比较简单就不上传了