赞
踩
初次接触安卓,做出来一个还能看的案例,类似小说阅读的APP,将源码记录一下
<?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>
<?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>
<?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>
<?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>
<?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>
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); } } }; //主UI线程 @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(); } /** * post请求线程 */ Runnable postRun = new Runnable() { PostUtils postUtils=new PostUtils(); int flag; String msg; @Override public void run() { // TODO Auto-generated method stub 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){ //TODO 登陆失败之后如何显示出JSON返回的数据?--全局变量; // 将服务器返回数据展示在当前页面,如何将服务器返回的数据展示到跳转之后的页面呢? //用户名或者密码错误,信息弹出在界面上,需要进行线程的处理 Message message=new Message(); message.what=COMPLETED; handler.sendMessage(message); }else{ //TODO 如何正常登陆之后将信息显示到新打开的活动中 //正常登陆 Intent intent=new Intent(LoginActivity.this, SuccessActivity.class); //在服务器查看当前用户的信息 //TODO 服务器需要将当前用户的姓名返回?还是在页面上获取?后者 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); //TODO 写好后端之后根据返回的数据解析 flag=jsonObject_userInfo.getInt("code"); JSONObject jsonObject1 = jsonObject_userInfo.getJSONObject("data"); //.getJSONArray("data"); //String username=jsonObject1.getString("username"); 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携带User数据到新的意图,数据的传输 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(); } } }; //点击注册按钮的话,跳转到注册页面进行注册 //TODO 为何一定要加上参数View,点击一次发出警告语句,点击第二次就报错并且结束程序 public void doReg(View view){ Intent intent=new Intent(this,RegisterActivity.class); startActivity(intent); } }
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; //设置全局变量用于接受返回的JSON信息 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); } } }; /** * post请求线程 */ Runnable postRun = new Runnable() { PostUtils postUtils=new PostUtils(); int flag; String msg; @Override public void run() { // TODO Auto-generated method stub try { //TODO --服务端需要转换成两个Servlet 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(); } } }; //点击注册按钮的话,跳转到注册页面进行注册 //TODO 为何一定要加上参数View public void toLogin(View view){ Intent intent=new Intent(this,LoginActivity.class); startActivity(intent); } }
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); } }
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,一个ImageView 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); //Button query02 = (Button) findViewById(R.id.btn_query02); //Button query03 = (Button) findViewById(R.id.btn_query03); //Button query01 = (Button) findViewById(R.id.btn_query01); //Button query04 = (Button) findViewById(R.id.btn_query04); //将从其他页面带过来的数据展示在当前页面上 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>(); //不同的TextView添加不同的点击事件 @Override public void onClick(View view) { //这里写错了,路径是不能够写到参数当中的 //stringHashMap.put("queryByUsernameUrl",queryByBooknameUrl); //追加参数 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); //TODO 写好后端之后根据返回的数据解析 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(); } } } }; }
需要加入gson和mysql连接的jar包
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 { //登陆,失败为0,成功为1 @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(); // 基类对象,回传给客户端的json对象 UserBean userBean = new UserBean(); // user的对象 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); // 将对象转化成json字符串 try { response.getWriter().println(json); // 将json数据传给客户端 } catch (Exception e) { e.printStackTrace(); } finally { response.getWriter().close(); // 关闭这个流,不然会发生错误的 } dbUtils.closeConnect(); // 关闭数据库连接} } }
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 { //注册,失败为0,成功为1 @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"); //TODO 也应返回相应的数据 if (username == null || username.equals("") || password == null || password.equals("")) { System.out.println("用户名或密码为空"); return; } // 请求数据库 DBUtils dbUtils = new DBUtils(); dbUtils.openConnect(); // 打开数据库连接 BaseBean data = new BaseBean(); // 基类对象,回传给客户端的json对象 UserBean userBean = new UserBean(); // user的对象 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); // 将对象转化成json字符串 try { response.getWriter().println(json); // 将json数据传给客户端 } catch (Exception e) { e.printStackTrace(); } finally { response.getWriter().close(); // 关闭这个流,不然会发生错误的 } dbUtils.closeConnect(); // 关闭数据库连接} } }
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 { //注册,失败为0,成功为1 @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 { //TODO 打印当前时间 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"); //TODO 也应返回相应的数据 if (username == null || username.equals("")) { System.out.println("用户名为空"); return; } // 请求数据库 DBUtils dbUtils = new DBUtils(); dbUtils.openConnect(); // 打开数据库连接 BaseBean data = new BaseBean(); // 基类对象,回传给客户端的json对象 UserBean userBean = new UserBean(); // user的对象 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); // 将对象转化成json字符串 try { response.getWriter().println(json); // 将json数据传给客户端 } catch (Exception e) { e.printStackTrace(); } finally { response.getWriter().close(); // 关闭这个流,不然会发生错误的 } dbUtils.closeConnect(); // 关闭数据库连接} } }
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 { //TODO 打印当前时间 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; //从数据库读取值,然后将数据封装成一个book对应的实体类 if (rs != null) { while (true) { try { if (!rs.next()) break; bookName=rs.getString("book_name"); context= rs.getString("context"); } catch (SQLException ex) { ex.printStackTrace(); } } } //将返回结果分装成一个实体类然后使用Json进行转换 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); // 将对象转化成json字符串 try { response.getWriter().println(json); // 将json数据传给客户端 } catch (Exception e) { e.printStackTrace(); } finally { response.getWriter().close(); // 关闭这个流,不然会发生错误的 } dbUtils.closeConnect(); // 关闭数据库连接} } }
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"; // 指定连接数据库的URL 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()); } } // 获得查询user表后的数据集 public ResultSet getUser() { // 创建 statement对象 try { sta = conn.createStatement(); // 执行SQL查询语句 rs = sta.executeQuery("select * from user"); } catch (SQLException e) { e.printStackTrace(); } return rs; } // 判断数据库中是否存在某个用户名及其密码,注册和登录的时候判断 public boolean isExistInDB(String username, String password) { boolean isFlag = false; // 创建 statement对象 try { System.out.println("判断用户名密码"); sta = conn.createStatement(); // 执行SQL查询语句 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; } // 注册 将用户名和密码插入到数据库(id设置的是自增长的,因此不需要插入) 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); // 执行SQL查询语句 return ps.execute(); } catch (SQLException e) { e.printStackTrace(); } return false; } //根据用户名查询用户信息(以及规定用户名不能够重复) public ResultSet queryByUsername(String username){ //使用预编译的方式进行查询 //String sql="select * from user where user_name='"+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; } }
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; } }
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; } }
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,后端由于比较简单就不上传了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。