Android实现注册登录头像上传等功能常规开发(Android端,服务器端开发实例)

标签: 注册登录Android开发servlet
2017-04-18 20:34  454人阅读  评论(1)  收藏  举报
  分类:
Android(18)   Java开发(5)   数据库(1) 

版权声明:本文为博主原创文章,未经博主允许不得转载。

目录(?)[+]

时隔半年再次敲动键盘,发现时间过得真心快。原本自己该干的事情被琐碎事情给耽搁了,现在想想该重新振奋起来好好努力。闲话到此,今天给大家带来的教程是常规化也是常见的登录注册上传头像等操作,本篇也是从项目中挑出部分,项目是真实测试的,完全能实现如上操作,所以各位不用担心,由于时间原因,就不连接服务器测试了,本篇文章也只是演示下过程。包括了客户端和服务器的部分程序,当然了该篇博客仅限学习,下面进入正文。下面是项目的注册登录部分在模拟器上的演示:

在开始讲解咱们的项目之前咱们先整理下思路。在学习本篇文章前请了解并学习下列相关知识:

  • okhttp网络请求库最新版本的使用方法(建议去github下载相应的okhttp工具类)
  • Mysql数据库进行数据存储
  • servlet相关知识(请参考 超详细servlet+jdbc+html+css实现后台管理登陆)
  • Base64图片编码
  • Tomcat服务器实现虚拟映射路径设置(在本篇文章中将图片保存在服务器的虚拟映射路径中)

注意:本篇文章可能不能完全把代码完全注释讲解,所以敬请大家有点耐心。

客户端:

  1. 编写注册界面的xml布局文件
  2. 实现注册界面的逻辑实现
  3. 编写登录界面的XML布局文件
  4. 实现登录界面的逻辑实现

首先我们看到客户端的整体的结构图:

注册界面布局:wyt_register.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. android:id="@+id/register"
  5. android:orientation="vertical"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:background="#f5f5f5"
  9. >
  10. <LinearLayout
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"
  13. android:orientation="vertical">
  14. <com.mero.wyt_register.widget.CustomTitleBar
  15. android:layout_width="match_parent"
  16. android:layout_height="80dp"
  17. app:text="用户注册"
  18. app:background_color="@color/mediumturquoise"
  19. />
  20. <LinearLayout
  21. android:layout_width="match_parent"
  22. android:layout_height="150dp"
  23. android:orientation="vertical"
  24. android:background="@color/mediumturquoise">
  25. <RelativeLayout
  26. android:layout_width="match_parent"
  27. android:layout_height="match_parent">
  28. <ImageView
  29. android:id="@+id/img_upload_img"
  30. android:layout_width="100dp"
  31. android:layout_height="100dp"
  32. android:layout_centerHorizontal="true"
  33. android:src="@drawable/menu_item_theme"/>
  34. <TextView
  35. android:id="@+id/tx_upload_img"
  36. android:layout_below="@id/img_upload_img"
  37. android:layout_width="wrap_content"
  38. android:layout_height="wrap_content"
  39. android:text="上传头像"
  40. android:layout_centerHorizontal="true"
  41. android:textSize="15sp"
  42. android:gravity="fill_vertical"
  43. android:textColor="#fff"/>
  44. </RelativeLayout>
  45. </LinearLayout>
  46. </LinearLayout>
  47. <LinearLayout
  48. android:layout_width="match_parent"
  49. android:layout_height="100dp"
  50. android:orientation="vertical"
  51. android:background="#FFF">
  52. <LinearLayout
  53. android:layout_width="match_parent"
  54. android:layout_height="50dp"
  55. android:orientation="horizontal">
  56. <ImageView
  57. android:id="@+id/img_register_account"
  58. android:layout_width="32dp"
  59. android:layout_height="32dp"
  60. android:src="@drawable/account"
  61. android:layout_marginLeft="10dp"
  62. android:layout_gravity="center_vertical"/>
  63. <EditText
  64. android:id="@+id/edt_register_account"
  65. android:layout_width="match_parent"
  66. android:layout_height="50dp"
  67. android:hint="账号"
  68. android:textColorHighlight="#77000000"
  69. android:textColor="#000000"
  70. android:maxLines="1"
  71. android:background="@null"
  72. android:gravity="center_vertical"
  73. android:paddingLeft="15dp"
  74. android:textSize="15sp"
  75. android:textColorHint="#77000000"
  76. />
  77. </LinearLayout>
  78. <TextView
  79. android:layout_width="match_parent"
  80. android:layout_height="1dp"
  81. android:background="#f5f5f5"/>
  82. <LinearLayout
  83. android:layout_width="match_parent"
  84. android:layout_height="match_parent"
  85. android:orientation="horizontal"
  86. android:background="#FFF"
  87. android:baselineAligned="false">
  88. <ImageView
  89. android:id="@+id/img_register_pwd"
  90. android:layout_width="32dp"
  91. android:layout_height="32dp"
  92. android:layout_marginLeft="10dp"
  93. android:src="@drawable/pwd"
  94. android:layout_gravity="center_vertical"/>
  95. <EditText
  96. android:id="@+id/edt_register_pwd"
  97. android:layout_width="match_parent"
  98. android:layout_height="match_parent"
  99. android:hint="密码"
  100. android:inputType="textPassword"
  101. android:maxLines="1"
  102. android:textSize="15sp"
  103. android:textColorHighlight="#77000000"
  104. android:textColor="#000000"
  105. android:background="@null"
  106. android:paddingLeft="15sp"
  107. android:textColorHint="#77000000"
  108. android:layout_weight="1" />
  109. </LinearLayout>
  110. </LinearLayout>
  111. <RelativeLayout
  112. android:layout_width="match_parent"
  113. android:layout_height="50dp"
  114. android:layout_marginTop="20dp">
  115. <com.mero.wyt_register.widget.RoundButton
  116. android:id="@+id/btn_to_register"
  117. android:layout_width="300dp"
  118. android:layout_height="50dp"
  119. android:text="注册"
  120. android:textColor="#FFF"
  121. android:textStyle="bold"
  122. android:textSize="15sp"
  123. android:gravity="center"
  124. android:layout_centerInParent="true"
  125. app:btnCornerRadius="10dp"
  126. app:btnSolidColor="@color/mediumturquoise"
  127. app:btnPressedRatio="1.5"
  128. />
  129. </RelativeLayout>
  130. </LinearLayout>
效果如下:

登录界面布局wyt_login.xml:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. android:orientation="vertical"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="#f5f5f5"
  8. >
  9. <com.mero.wyt_register.widget.CustomTitleBar
  10. android:layout_width="match_parent"
  11. android:layout_height="80dp"
  12. app:text="用户登录"
  13. app:background_color="@color/mediumturquoise"
  14. />
  15. <LinearLayout
  16. android:layout_width="match_parent"
  17. android:layout_height="100dp"
  18. android:orientation="vertical"
  19. android:background="#FFF">
  20. <LinearLayout
  21. android:layout_width="match_parent"
  22. android:layout_height="50dp"
  23. android:orientation="horizontal">
  24. <ImageView
  25. android:id="@+id/img_login_account"
  26. android:layout_width="32dp"
  27. android:layout_height="32dp"
  28. android:src="@drawable/account"
  29. android:layout_marginLeft="10dp"
  30. android:layout_gravity="center_vertical"/>
  31. <EditText
  32. android:id="@+id/edt_login_account"
  33. android:layout_width="match_parent"
  34. android:layout_height="50dp"
  35. android:hint="账号"
  36. android:textColorHighlight="#77000000"
  37. android:textColor="#000000"
  38. android:maxLines="1"
  39. android:background="@null"
  40. android:gravity="center_vertical"
  41. android:paddingLeft="15dp"
  42. android:textSize="15sp"
  43. android:textColorHint="#77000000"
  44. />
  45. </LinearLayout>
  46. <TextView
  47. android:layout_width="match_parent"
  48. android:layout_height="1dp"
  49. android:background="#f5f5f5"/>
  50. <LinearLayout
  51. android:layout_width="match_parent"
  52. android:layout_height="match_parent"
  53. android:orientation="horizontal"
  54. android:background="#FFF"
  55. android:baselineAligned="false">
  56. <ImageView
  57. android:id="@+id/img_login_pwd"
  58. android:layout_width="32dp"
  59. android:layout_height="32dp"
  60. android:layout_marginLeft="10dp"
  61. android:src="@drawable/pwd"
  62. android:layout_gravity="center_vertical"/>
  63. <EditText
  64. android:id="@+id/edt_login_pwd"
  65. android:layout_width="match_parent"
  66. android:layout_height="match_parent"
  67. android:inputType="textPassword"
  68. android:hint="密码"
  69. android:maxLines="1"
  70. android:textSize="15sp"
  71. android:textColorHighlight="#77000000"
  72. android:textColor="#000000"
  73. android:background="@null"
  74. android:paddingLeft="15sp"
  75. android:textColorHint="#77000000"
  76. android:layout_weight="1" />
  77. </LinearLayout>
  78. </LinearLayout>
  79. <RelativeLayout
  80. android:layout_width="match_parent"
  81. android:layout_height="50dp"
  82. android:layout_marginTop="20dp">
  83. <com.mero.wyt_register.widget.RoundButton
  84. android:id="@+id/btn_login_click_to_login"
  85. android:layout_width="300dp"
  86. android:layout_height="50dp"
  87. android:text="立即登录"
  88. android:textColor="@color/white"
  89. android:textSize="15sp"
  90. android:gravity="center"
  91. android:layout_centerInParent="true"
  92. app:btnCornerRadius="10dp"
  93. app:btnSolidColor="@color/mediumturquoise"
  94. app:btnPressedRatio="1.5"
  95. />
  96. </RelativeLayout>
  97. <RelativeLayout
  98. android:layout_width="match_parent"
  99. android:layout_height="50dp">
  100. <TextView
  101. android:id="@+id/tx_login_click_to_register"
  102. android:layout_width="wrap_content"
  103. android:layout_height="match_parent"
  104. android:layout_alignParentRight="true"
  105. android:text="点击注册"
  106. android:textColor="#33aa44"
  107. android:textSize="15sp"
  108. android:textStyle="bold"
  109. android:paddingRight="25dp"
  110. android:paddingTop="25dp"
  111. />
  112. </RelativeLayout>
  113. </LinearLayout>
登录界面效果如下:
接下来是我们的注册界面的逻辑代码:

RegisterAty.java

[java]  view plain copy
  1. package com.mero.wyt_register.activity;
  2. import android.app.ProgressDialog;
  3. import android.content.Intent;
  4. import android.database.Cursor;
  5. import android.graphics.Bitmap;
  6. import android.graphics.BitmapFactory;
  7. import android.net.Uri;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.provider.MediaStore;
  11. import android.text.TextUtils;
  12. import android.view.Gravity;
  13. import android.view.View;
  14. import android.view.animation.AnimationSet;
  15. import android.view.animation.TranslateAnimation;
  16. import android.widget.EditText;
  17. import android.widget.ImageView;
  18. import android.widget.Toast;
  19. import com.mero.wyt_register.Base.BaseSwipeBackLayout;
  20. import com.mero.wyt_register.Config;
  21. import com.mero.wyt_register.R;
  22. import com.mero.wyt_register.net.RegisterAction;
  23. import com.mero.wyt_register.utils.AppUtils;
  24. import com.mero.wyt_register.utils.Base64Utils;
  25. import com.mero.wyt_register.utils.SDCardUtils;
  26. import com.mero.wyt_register.widget.RoundButton;
  27. import com.mero.wyt_register.widget.SelectPicPopupWindow;
  28. /**
  29. * Created by chenlei on 2016/11/17.
  30. */
  31. public class RegisterAty extends BaseSwipeBackLayout implements View.OnClickListener {
  32. private ImageView img_upload;
  33. private EditText edt_account = null;
  34. private EditText edt_pwd = null;
  35. private RoundButton btn_register = null;
  36. private static final int RESULT_OPEN_IMAGE = 1;
  37. private Bitmap bitmap ;//存放裁剪后的头像
  38. private String fileName;//头像名称
  39. private String picturePath;//头像路径
  40. private ProgressDialog pd;//进度条
  41. private static final int DISMISS = 1000;//进度条消失
  42. private SelectPicPopupWindow selectPicPopupWindow;
  43. @Override
  44. public void initView() {
  45. img_upload = (ImageView) findViewById(R.id.img_upload_img);
  46. edt_account = (EditText) findViewById(R.id.edt_register_account);
  47. edt_pwd = (EditText) findViewById(R.id.edt_register_pwd);
  48. img_upload.setOnClickListener(this);
  49. btn_register = (RoundButton) findViewById(R.id.btn_to_register);
  50. btn_register.setOnClickListener(this);
  51. }
  52. @Override
  53. public void initData() {
  54. }
  55. private final Handler handler = new Handler(){
  56. @Override
  57. public void handleMessage(Message msg) {
  58. if(msg.what == DISMISS){
  59. pd.dismiss();
  60. }
  61. }
  62. };
  63. @Override
  64. public int getLayoutResourceId() {
  65. return R.layout.wyt_register;
  66. }
  67. @Override
  68. public int getDialogIcon() {
  69. return 0;
  70. }
  71. @Override
  72. public int setStatusBarColor() {
  73. return 0;
  74. }
  75. private static final int CAMERA_REQUEST_CODE = 1;//拍照返回码
  76. private static final int GALLERY_REQUEST_CODE = 2;//相册返回码
  77. @Override
  78. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  79. super.onActivityResult(requestCode, resultCode, data);
  80. //如果是拍照返回
  81. if(requestCode==CAMERA_REQUEST_CODE&&resultCode==RESULT_OK&&data!=null) {
  82. Uri uri = data.getData();
  83. if (uri != null) {
  84. Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
  85. if (cursor.moveToFirst()) {
  86. picturePath = cursor.getString(cursor.getColumnIndex("_data"));
  87. fileName = getBitmapName(picturePath);
  88. bitmap = AppUtils.toRoundBitmap(BitmapFactory.decodeFile(picturePath));
  89. //进行裁剪
  90. img_upload.setImageBitmap(bitmap);
  91. }
  92. } else {
  93. Toast.makeText(this,"保存照片失败",Toast.LENGTH_SHORT).show();
  94. return;
  95. }
  96. }
  97. //如果是相册返回
  98. if(requestCode==GALLERY_REQUEST_CODE&&resultCode==RESULT_OK&&null!=data){
  99. Uri selectedImage = data.getData();
  100. String[] filePathColumn = {MediaStore.Images.Media.DATA};
  101. Cursor cursor = getContentResolver().query(selectedImage,
  102. filePathColumn, null, null, null);
  103. cursor.moveToFirst();
  104. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  105. picturePath = cursor.getString(columnIndex);
  106. fileName = getBitmapName(picturePath);
  107. cursor.close();
  108. //裁剪为圆形头像
  109. if(SDCardUtils.isSDCardEnable()){
  110. bitmap = AppUtils.toRoundBitmap(BitmapFactory.decodeFile(picturePath));
  111. img_upload.setImageBitmap(bitmap);//设置到图片
  112. }else {
  113. return;
  114. }
  115. }else {
  116. return;
  117. }
  118. }
  119. //获取图片的名称
  120. public String getBitmapName(String picPath){
  121. String bitmapName="";
  122. String[]  s = picPath.split("/");
  123. bitmapName = s[s.length-1];
  124. return bitmapName;
  125. }
  126. @Override
  127. public void onClick(View v) {
  128. switch (v.getId()) {
  129. case R.id.img_upload_img:
  130. //判断是否从相册或者调用相机实现
  131. selectPicPopupWindow = new SelectPicPopupWindow(RegisterAty.this, new View.OnClickListener() {
  132. @Override
  133. public void onClick(View v) {
  134. selectPicPopupWindow.dismiss();
  135. switch (v.getId()){
  136. case R.id.btn_select_camera:
  137. //从相机拍照
  138. Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  139. startActivityForResult(i,1);
  140. break;
  141. case R.id.btn_select_pic_photo_lib:
  142. //从图库选择照片
  143. Intent ii = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  144. startActivityForResult(ii, RESULT_OPEN_IMAGE);
  145. break;
  146. }
  147. }
  148. });
  149. View view = RegisterAty.this.findViewById(R.id.register);
  150. selectPicPopupWindow.showAtLocation(view, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
  151. AnimationSet animationSet = new AnimationSet(true);
  152. TranslateAnimation translateAnimation = new TranslateAnimation(1,0,1,0);
  153. translateAnimation.setDuration(1000);
  154. animationSet.addAnimation(translateAnimation);
  155. view.startAnimation(translateAnimation);
  156. break;
  157. case R.id.btn_to_register:
  158. //点击的是注册按钮
  159. final String wyt_account = edt_account.getText().toString();//获取账号
  160. final String wyt_pwd = edt_pwd.getText().toString();//获取密码
  161. if(TextUtils.isEmpty(wyt_account)){
  162. Toast.makeText(RegisterAty.this,"账号不能为空",Toast.LENGTH_SHORT).show();
  163. return;
  164. }
  165. if(TextUtils.isEmpty(wyt_pwd)){
  166. Toast.makeText(RegisterAty.this,"密码不能为空",Toast.LENGTH_SHORT).show();
  167. return;
  168. }
  169. if(wyt_account.length()>20){
  170. Toast.makeText(RegisterAty.this,"您输入的账号过长",Toast.LENGTH_SHORT).show();
  171. return;
  172. }
  173. if(wyt_pwd.length()>20){
  174. Toast.makeText(RegisterAty.this,"您输入的密码过长",Toast.LENGTH_SHORT).show();
  175. return;
  176. }
  177. pd = ProgressDialog.show(this,"温馨提示","正在注册...",false,true);
  178. if(null!=bitmap){
  179. //截取图片后缀
  180. String base64img = Base64Utils.bitmaptoString(bitmap);
  181. //进行用户注册
  182. new RegisterAction(Config.URL, Config.KEY_REGISTER, wyt_account, wyt_pwd, base64img, new RegisterAction.ISuccessCallback() {
  183. @Override
  184. public void onSuccess(String response, int id) {
  185. pd.setMessage("注册成功");
  186. handler.sendEmptyMessageDelayed(DISMISS,1000);
  187. showActivity(RegisterAty.this,LoginAty.class);
  188. }
  189. }, new RegisterAction.IFailCallback() {
  190. @Override
  191. public void onFail(String failMsg) {
  192. pd.setMessage("注册失败"+failMsg);
  193. handler.sendEmptyMessageDelayed(DISMISS,1000);
  194. }
  195. });
  196. }
  197. break;
  198. default:
  199. break;
  200. }
  201. }
  202. private String getPicType(String picName){
  203. String[] s = picName.split(".");
  204. //数组长度
  205. return s[s.length-1];
  206. }
  207. }
然后对注册界面的网络请求进行封装:

RegisterAction.java

[java]  view plain copy
  1. package com.mero.wyt_register.net;
  2. import android.util.Log;
  3. import com.mero.wyt_register.Config;
  4. import com.zhy.http.okhttp.OkHttpUtils;
  5. import com.zhy.http.okhttp.callback.StringCallback;
  6. import org.json.JSONException;
  7. import org.json.JSONObject;
  8. import java.io.File;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. import okhttp3.Call;
  12. import static android.R.attr.action;
  13. import static com.google.android.gms.internal.zzs.TAG;
  14. import static com.mero.wyt_register.R.drawable.account;
  15. import static com.zhy.http.okhttp.OkHttpUtils.post;
  16. /**
  17. * Created by chenlei on 2016/11/17.
  18. */
  19. public class RegisterAction {
  20. /*
  21. * 注册
  22. * */
  23. public RegisterAction(String url, String action, String account, String pwd, String picBase64, final ISuccessCallback successCallback, final IFailCallback failCallback){
  24. OkHttpUtils
  25. .post()
  26. .url(url)
  27. .addParams(Config.KEY_ACTION,action)
  28. .addParams(Config.KEY_ACCOUNT,account)
  29. .addParams(Config.KEY_PWD,pwd)
  30. .addParams(Config.KEY_USER_ICON,picBase64)
  31. .build()
  32. .execute(new StringCallback() {
  33. @Override
  34. public void onError(Call call, Exception e, int id) {
  35. if(null!=failCallback){
  36. Log.e(TAG,"注册失败"+e.getMessage());
  37. failCallback.onFail(e.getMessage());
  38. }
  39. }
  40. @Override
  41. public void onResponse(String response, int id) {
  42. try {
  43. JSONObject jsonObject = new JSONObject(response);
  44. int status = jsonObject.getInt(Config.KEY_STATUS);
  45. int errCode = jsonObject.getInt(Config.KEY_ERR_CODE);
  46. if(status==1){
  47. successCallback.onSuccess(response,id);
  48. }else if(status==0){
  49. failCallback.onFail(response);
  50. }
  51. } catch (JSONException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. });
  56. }
  57. public interface ISuccessCallback{
  58. void onSuccess(String response,int id);
  59. };
  60. public interface IFailCallback{
  61. void onFail(String errCause);
  62. }
  63. }

接下来上登录界面逻辑代码:

LoginAty.java

[java]  view plain copy
  1. package com.mero.wyt_register.activity;
  2. import android.app.ProgressDialog;
  3. import android.content.Context;
  4. import android.content.SharedPreferences;
  5. import android.graphics.Bitmap;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.text.TextUtils;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.widget.EditText;
  12. import android.widget.TextView;
  13. import android.widget.Toast;
  14. import com.mero.wyt_register.Base.BaseSwipeBackLayout;
  15. import com.mero.wyt_register.Config;
  16. import com.mero.wyt_register.MyApplication;
  17. import com.mero.wyt_register.R;
  18. import com.mero.wyt_register.bean.User;
  19. import com.mero.wyt_register.db.DbHelper;
  20. import com.mero.wyt_register.net.LoginAction;
  21. import com.mero.wyt_register.utils.Base64Utils;
  22. import com.mero.wyt_register.widget.RoundButton;
  23. /**
  24. * Created by chenlei on 2016/11/16.
  25. */
  26. public class LoginAty extends BaseSwipeBackLayout implements View.OnClickListener{
  27. private static final String TAG = "LoginAty";
  28. private EditText edt_account = null;
  29. private EditText edt_pwd = null;
  30. private RoundButton btn_login_click_to_login;
  31. private TextView tx_register;
  32. private ProgressDialog pd;//进度条
  33. private static  final int DISMISS = 0 ;
  34. private User user ;
  35. @Override
  36. public void initData() {
  37. }
  38. @Override
  39. public void initView() {
  40. edt_account = (EditText) findViewById(R.id.edt_login_account);
  41. edt_pwd = (EditText) findViewById(R.id.edt_login_pwd);
  42. tx_register = (TextView) findViewById(R.id.tx_login_click_to_register);
  43. btn_login_click_to_login = (RoundButton) findViewById(R.id.btn_login_click_to_login);
  44. btn_login_click_to_login.setOnClickListener(this);
  45. tx_register.setOnClickListener(this);
  46. }
  47. private final Handler handler = new Handler(){
  48. @Override
  49. public void handleMessage(Message msg) {
  50. if(msg.what==DISMISS){
  51. pd.dismiss();
  52. }
  53. }
  54. };
  55. @Override
  56. public int getLayoutResourceId() {
  57. return R.layout.wyt_login;
  58. }
  59. @Override
  60. public int getDialogIcon() {
  61. return 0;
  62. }
  63. @Override
  64. public int setStatusBarColor() {
  65. return 0;
  66. }
  67. @Override
  68. public void onClick(View v) {
  69. switch (v.getId()){
  70. case R.id.btn_login_click_to_login:
  71. //点击的是登录按钮
  72. final String wyt_account = edt_account.getText().toString();//获取账号
  73. final String wyt_pwd = edt_pwd.getText().toString();//获取密码
  74. if(TextUtils.isEmpty(wyt_account)){
  75. Toast.makeText(LoginAty.this,"账号不能为空",Toast.LENGTH_SHORT).show();
  76. return;
  77. }
  78. if(TextUtils.isEmpty(wyt_pwd)){
  79. Toast.makeText(LoginAty.this,"密码不能为空",Toast.LENGTH_SHORT).show();
  80. return;
  81. }
  82. if(wyt_account.length()>20){
  83. Toast.makeText(LoginAty.this,"您输入的账号过长",Toast.LENGTH_SHORT).show();
  84. return;
  85. }
  86. if(wyt_pwd.length()>20){
  87. Toast.makeText(LoginAty.this,"您输入的密码过长",Toast.LENGTH_SHORT).show();
  88. return;
  89. }
  90. String token =  Config.getTokenFromPreferences(this);
  91. Log.e(TAG,"token的值"+token);
  92. //显示进度对话框
  93. pd = ProgressDialog.show(this,"温馨提示","正在登录",false,true);
  94. new LoginAction(Config.URL, Config.KEY_LOGIN, wyt_account, wyt_pwd, "", new LoginAction.ISuccessCallback() {
  95. @Override
  96. public void onSuccess(String s, String token) {
  97. pd.setMessage("登录成功");
  98. //把token保存起来
  99. SharedPreferences sharedPreferences = MyApplication.getMyApplication().getSharedPreferences(Config.ID, Context.MODE_PRIVATE);
  100. SharedPreferences.Editor editor = sharedPreferences.edit();
  101. editor.putString(Config.KEY_TOKEN,token);
  102. editor.commit();
  103. //获取头像
  104. Bitmap bitmap = Base64Utils.stringtoBitmap(s);
  105. user = new User();
  106. user.setWyt_account(wyt_account);
  107. user.setWyt_pwd(wyt_pwd);
  108. user.setUser_icon(bitmap);
  109. //保存该用户到数据库中
  110. new DbHelper(LoginAty.this).insert(user,"user_wyt","person");
  111. pd.dismiss();
  112. showActivity(LoginAty.this,MainActivity.class);
  113. }
  114. }, new LoginAction.IFailCallback() {
  115. @Override
  116. public void onFail(String s) {
  117. pd.setMessage("登录失败");
  118. handler.sendEmptyMessageDelayed(DISMISS,1000);
  119. }
  120. });
  121. //                }
  122. break;
  123. case R.id.tx_login_click_to_register:
  124. showActivity(LoginAty.this,RegisterAty.class);
  125. break;
  126. }
  127. }
  128. @Override
  129. protected void onDestroy() {
  130. super.onDestroy();
  131. }
  132. }

下面是登录网络逻辑的封装代码:

LoginAction.java

[java]  view plain copy
  1. package com.mero.wyt_register.net;
  2. import android.graphics.Bitmap;
  3. import android.text.TextUtils;
  4. import android.util.Log;
  5. import com.mero.wyt_register.Config;
  6. import com.mero.wyt_register.utils.Base64Utils;
  7. import com.zhy.http.okhttp.OkHttpUtils;
  8. import com.zhy.http.okhttp.callback.StringCallback;
  9. import org.json.JSONException;
  10. import org.json.JSONObject;
  11. import okhttp3.Call;
  12. /**
  13. * Creaed by chenlei on 2016/11/15.
  14. */
  15. public class LoginAction {
  16. private static  final  String TAG = "loginService";
  17. //登录账号密码
  18. public LoginAction(String url, String action, String account, String pwd, String token, final ISuccessCallback successCallback, final IFailCallback failCallback){
  19. OkHttpUtils.post()
  20. .url(url)
  21. .addParams(Config.KEY_ACTION,action)
  22. .addParams(Config.KEY_ACCOUNT,account)
  23. .addParams(Config.KEY_PWD,pwd)
  24. .addParams(Config.KEY_TOKEN,token)
  25. .build().execute(new StringCallback() {
  26. @Override
  27. public void onError(Call call, Exception e, int id) {
  28. if(failCallback!=null){
  29. failCallback.onFail(e.getMessage());
  30. }
  31. }
  32. @Override
  33. public void onResponse(String response, int id) {
  34. try {
  35. JSONObject jsonObject =new JSONObject(response);
  36. int status = jsonObject.getInt("status");
  37. String iconStrBase64 = jsonObject.getString("user_icon");
  38. String token = jsonObject.getString("token");
  39. if(status==1){
  40. if(null!=successCallback){
  41. successCallback.onSuccess(iconStrBase64,token);
  42. }
  43. }else if(status==0){
  44. if(null!=failCallback){
  45. failCallback.onFail(response);
  46. }
  47. }
  48. } catch (JSONException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. });
  53. }
  54. public interface ISuccessCallback{
  55. void onSuccess(String s,String token);
  56. }
  57. public interface IFailCallback{
  58. void onFail(String s);
  59. }
  60. }

服务器端:

通过servlet实现对Action的处理,本实例仅采用了唯一的一个OnlyServlet。如果对servlet的使用不太会的话建议看下我的这篇关于servlet处理网页客户端的请求。本篇文章中不再累赘。首先我们来看看服务器的简单结构。服务器端仅仅对注册和登录,头像保存部分。
先上最关键的核心处理部分,本文中的登录注册等Action都在该servlet中处理。

OnlyServlet.java

[java]  view plain copy
  1. package com.wyt_register;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.json.JSONException;
  12. import org.json.JSONStringer;
  13. import com.wyt_register.db.UserDao;
  14. import com.wyt_register.md5Tool.Base64Utils;
  15. import com.wyt_register.md5Tool.Md5Utils;
  16. /**
  17. * Servlet implementation class OnlyServlet
  18. */
  19. @WebServlet("/OnlyServlet")
  20. public class OnlyServlet extends HttpServlet {
  21. private static final long serialVersionUID = 1L;
  22. /**
  23. * @see HttpServlet#HttpServlet()
  24. */
  25. public OnlyServlet() {
  26. super();
  27. // TODO Auto-generated constructor stub
  28. }
  29. /**
  30. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  31. */
  32. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  33. // TODO Auto-generated method stub
  34. String action = null;//根据请求的行为进行相应的操作
  35. if((action=request.getParameter(Config.KEY_ACTION))!=null){
  36. switch(action){
  37. //          如果是注册
  38. case Config.KEY_REGISTER:
  39. System.out.println("正在请求注册");
  40. //              用户注册的账号
  41. String account_register = request.getParameter(Config.KEY_USER_ACCOUNT);
  42. System.out.println(account_register);
  43. //              用户注册的密码
  44. String pwd_register = request.getParameter(Config.KEY_USER_PWD);
  45. System.out.println(pwd_register);
  46. //              用户上传的头像
  47. String icon = request.getParameter(Config.KEY_USER_ICON);
  48. if((null!=account_register)&&(null!=pwd_register)&&(null!=icon)){
  49. //开启注册事务
  50. //把唯一的账号名的md5值作为图片的名字
  51. StringBuilder sb0 = new StringBuilder("");
  52. //保存到数据库中的头像图片路径
  53. sb0.append("/image/").append(Md5Utils.encode(account_register)).append(".png");
  54. String icon_addr = sb0.toString();
  55. System.out.println("头像图片地址:"+icon_addr);
  56. StringBuilder sb1 = new StringBuilder("");
  57. //写入到本地的头像图片路径
  58. sb1.append(Config.ADDR_ICON).append(Md5Utils.encode(account_register)).append(".png");
  59. String local_icon_addr = sb1.toString();
  60. System.out.println("保存到本地的地址"+local_icon_addr);
  61. PrintWriter writer =response.getWriter();
  62. //查询用户是否已经注册过
  63. try {
  64. ResultSet set = UserDao.query(account_register);
  65. //没注册过,需要注册
  66. if(!set.next()){
  67. //保存上传的头像至本地
  68. boolean isSuccessToSaveImageToLocal = Base64Utils.getPicFormatBASE64(icon,local_icon_addr );
  69. if(isSuccessToSaveImageToLocal){
  70. //头像上传成功后然后再插入账号密码到数据库
  71. boolean isSuccessToRegister = UserDao.insert(new Object[]{Config.KEY_ID,Config.KEY_USER_ACCOUNT,Config.KEY_USER_PWD,Config.KEY_USER_ICON_ADDR},new Object[]{null,account_register,pwd_register,icon_addr});
  72. if(isSuccessToRegister){
  73. //注册成功
  74. writer.print("{\"status\":1,\"errCode\":0x00000000}");
  75. }else{
  76. //注册失败
  77. writer.print("{\"status\":0,\"errCode\":0x00000001}");
  78. }
  79. }
  80. }else{
  81. //注册过了
  82. writer.print("{\"status\":0,\"errCode\":0x00000010}");
  83. }
  84. } catch (SQLException e) {
  85. // TODO Auto-generated catch block
  86. e.printStackTrace();
  87. }
  88. }
  89. break;
  90. //          如果是登录
  91. case Config.KEY_LOGIN:
  92. PrintWriter writer = response.getWriter();
  93. //              用户登录的账号
  94. String account_login = request.getParameter(Config.KEY_USER_ACCOUNT);
  95. System.out.println("账号:"+account_login);
  96. //              用户登录的密码
  97. String pwd_login = request.getParameter(Config.KEY_USER_PWD);
  98. System.out.println("密码"+pwd_login);
  99. //              用户登录的token
  100. String token = request.getParameter(Config.KEY_TOKEN);
  101. System.out.println("token的值是"+token);
  102. //如果用户采用账号密码登录
  103. if((!account_login.equals(""))&&(!pwd_login.equals(""))&&token.equals("")){
  104. //查询数据库,是否存在
  105. try {
  106. System.out.println("正在查询数据库");
  107. ResultSet rs = UserDao.query(account_login);
  108. //如果该账号存在于数据库
  109. if(rs.next()){
  110. //获取该用户的密码
  111. String pwd = rs.getString(3);
  112. System.out.println("pwd:"+pwd);
  113. String icon_usr_addr = rs.getString(4);
  114. System.out.println(icon_usr_addr);
  115. if(pwd_login.equals(pwd)){
  116. //登录成功
  117. //获取头像地址
  118. String s[] = rs.getString(4).split("/");
  119. String usr_exact_addr ="F:/webapps/Images/"+s[s.length-1];
  120. System.out.println(usr_exact_addr);
  121. //得到base64字符串
  122. String base64img = Base64Utils.imageToBase64(usr_exact_addr);
  123. try {
  124. String s1 = new JSONStringer().object()
  125. .key("status")
  126. .value(1)
  127. .key("errCode")
  128. .value("0x0")
  129. .key("user_icon")
  130. .value(base64img)
  131. .endObject()
  132. .toString();
  133. writer.print(s1);
  134. } catch (JSONException e) {
  135. // TODO Auto-generated catch block
  136. e.printStackTrace();
  137. }
  138. }else{
  139. //登录失败
  140. try {
  141. String s2 = new JSONStringer().object()
  142. .key("status")
  143. .value(0)
  144. .key("errCode")
  145. .value("0x00000100")
  146. .endObject()
  147. .toString();
  148. writer.print(s2);
  149. } catch (JSONException e) {
  150. // TODO Auto-generated catch block
  151. e.printStackTrace();
  152. }
  153. }
  154. }else{
  155. //该账户不存在
  156. try {
  157. String s3 = new JSONStringer().object()
  158. .key("status")
  159. .value(0)
  160. .key("errCode")
  161. .value("0x00000011")
  162. .endObject()
  163. .toString();
  164. writer.println(s3);;
  165. } catch (JSONException e) {
  166. // TODO Auto-generated catch block
  167. e.printStackTrace();
  168. }
  169. }
  170. } catch (SQLException e) {
  171. // TODO Auto-generated catch block
  172. e.printStackTrace();
  173. }
  174. }
  175. //如果用户采用token登录
  176. if(token!=null){
  177. }
  178. break;
  179. }
  180. }
  181. }
  182. /**
  183. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  184. */
  185. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  186. // TODO Auto-generated method stub
  187. doGet(request, response);
  188. }
  189. }

下面是在上面的servlet封装的关于数据库Dao的逻辑处理部分:

BaseDao.java

[java]  view plain copy
  1. package com.wyt_register.db;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. public abstract class BaseDao {
  6. public static java.sql.Connection conn;
  7. static java.sql.Statement statement;
  8. BaseDao(){
  9. conn = DbUtils.getConnection();//打开数据连接
  10. try {
  11. statement = conn.createStatement();
  12. initStatement(statement);
  13. } catch (SQLException e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. }
  17. }
  18. /**
  19. * 该方法用于得到实例化Statement接口对象
  20. * @param statement
  21. */
  22. public abstract void initStatement(Statement statement);
  23. /**
  24. * 用于插入数据
  25. * @param b1    键名
  26. * @param b2    键值
  27. * @throws SQLException
  28. */
  29. public  boolean insert(String tableName,Object[] b1,Object[] b2){
  30. StringBuilder sb = new StringBuilder();
  31. sb.append("INSERT INTO ").append("`").append(tableName).append("`").append("(");
  32. for(Object ob:b1){
  33. sb.append((String)ob).append(",");
  34. }
  35. sb.deleteCharAt(sb.length()-1);
  36. sb.append(")").append(" ").append("values").append("(");
  37. for(Object ob:b2){
  38. if(ob instanceof Integer){
  39. sb.append((Integer)ob).append(",");
  40. }
  41. if(ob instanceof java.lang.String){
  42. sb.append("'").append((String)ob).append("'").append(",");
  43. }
  44. if(ob instanceof java.lang.Float){
  45. sb.append((Float)ob).append(",");
  46. }
  47. if(ob instanceof java.lang.Double){
  48. sb.append((Double)ob).append(",");
  49. }
  50. if(ob==null){
  51. sb.append("null").append(",");
  52. }
  53. }
  54. sb.deleteCharAt(sb.length()-1);
  55. sb.append(")");
  56. System.out.println(sb.toString());
  57. String sql = sb.toString();
  58. int row;
  59. try {
  60. row = statement.executeUpdate(sql);
  61. if(row>0){
  62. //插入成功
  63. return true;
  64. }
  65. DbUtils.closeConnection(conn);
  66. DbUtils.closeStatement(statement);
  67. } catch (SQLException e) {
  68. // TODO Auto-generated catch block
  69. e.printStackTrace();
  70. }
  71. return false;
  72. }
  73. /**
  74. * 该方法用来查询数据库某表中的某一字段值
  75. * @param tableName 表名
  76. * @param column    字段
  77. * @param stringToQuery 查询的参数
  78. */
  79. public  ResultSet queryExcute(String tableName,String column,String stringToQuery){
  80. String sql;
  81. ResultSet set = null;
  82. StringBuilder sb = new StringBuilder();
  83. sb.append("SELECT * FROM ").append("`").append(tableName).append("`").append(" ").append("where ").append(column).append("=")
  84. .append("'").append(stringToQuery).append("'");
  85. sql = sb.toString();
  86. try {
  87. set = statement.executeQuery(sql);
  88. if(null==set){
  89. return null;
  90. }
  91. } catch (SQLException e) {
  92. // TODO Auto-generated catch block
  93. e.printStackTrace();
  94. }
  95. return set;
  96. }
  97. }

UserDao.java

[java]  view plain copy
  1. package com.wyt_register.db;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. import com.wyt_register.Config;
  6. public class UserDao extends BaseDao{
  7. public Statement statement;
  8. public UserDao() {
  9. // TODO Auto-generated constructor stub
  10. System.out.println("正在执行RegisterDao");
  11. }
  12. @Override
  13. public void initStatement(Statement statement) {
  14. // TODO Auto-generated method stub
  15. this.statement = statement;
  16. }
  17. public static boolean insert(Object[] b1,Object[] b2) throws SQLException{
  18. return new UserDao().insert( com.wyt_register.Config.USER_TABLE, b1, b2);
  19. }
  20. public static ResultSet query(String account) throws SQLException{
  21. ResultSet set=new UserDao().queryExcute(com.wyt_register.Config.USER_TABLE, Config.KEY_USER_ACCOUNT, account);
  22. return set;
  23. }
  24. }<span style="color:#ff0000;">
  25. </span>

servlet配置文件:web.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <display-name>py02</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12. <servlet>
  13. <servlet-name>OnlyServlet</servlet-name>
  14. <servlet-class>com.wyt_register.OnlyServlet</servlet-class>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>OnlyServlet</servlet-name>
  18. <url-pattern>/</url-pattern>
  19. </servlet-mapping>
  20. </web-app>

其他几个文件我就不一一放上来了,具体的我在这里打包服务器的代码。服务器端代码下载:有什么问题可以加我QQ790710371或者发送问题至邮箱790710371@qq.com。

服务器端代码下载

Android实现注册登录头像上传等功能常规开发(Android端,服务器端开发实例)相关推荐

  1. java注册头像_注册页面头像上传的实现(javaweb相关)

    注册页面头像上传的实现: 1. 注册页面:register.jsp 两种方式实现图片上传: pageEncoding="UTF-8"%> register body{ mar ...

  2. php的注册头像上传,用Ajax实现注册与头像上传功能

    这次给大家带来用Ajax实现注册与头像上传功能,Ajax实现注册与头像上传功能的注意事项有哪些,下面就是实战案例,一起来看一下. 在初次接触ajax后,我们做了一个crm训练的项目,大多数小组都有注册 ...

  3. 小程序图片裁剪插件image-cropper实现个人头像上传裁剪功能

    小程序图片裁剪插件image-cropper实现个人头像上传裁剪功能 参考文档:小程序图片裁剪插件 image-cropper 整体效果流程图 一.第一步引入image-cropper,放在dist文 ...

  4. Android--利用Bmob实现头像上传下载功能

    声明: 本文使用Bmob作为云后台,实现一个简简单单的头像的选取.截取.上传.下载功能的实现. 编码环境:Android Studio2.1.1 运行环境:Miui8.6.8.18(安卓版本号6.0. ...

  5. web实现QQ头像上传截取功能

    由于最近一段时间比较忙,发现好久没写博客了,给大家分享下最近搞的logo上传截取功能.在实现这个功能之前找了一些jq的插件,最后选定了cropper在github中可以找到. 具体的思路是1:选择上传 ...

  6. SpringBoot实现注册时头像上传与下载

    一.说明 1.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data. 2.SpringMVC为文件上传提供了直接的支持,这种支持是通过 ...

  7. 优酷java_youtubie 仿优酷的视频网站,采用JAVA开发,支持Oracle数据库。主要功能包含注册登录, 上传 Jsp/Servlet 238万源代码下载- www.pudn.com...

    文件名称: youtubie下载 收藏√  [ 5  4  3  2  1 ] 开发工具: Java 文件大小: 12657 KB 上传时间: 2015-04-23 下载次数: 1 详细说明:仿优酷的 ...

  8. Android个人中心的头像上传,图片编码及截取

    首先需要有网络权限,然后我们这里匹配的网络请求是之前封装好的Okhttp,Okhttp的下载地址 非常的简单方便,直接复制进去,依赖一下包,然后调用方法即可. 这里是把图片转换成Base64.deco ...

  9. springMVC+jcrop实现头像上传截图功能

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

最新文章

  1. 如何禁止浏览器自动填充
  2. 分叉币众多,为什么说只有BCH能活下来?
  3. HDU OJ 5437 Alisha’s Party 2015online A
  4. SOCKS代理工具EarthWorm、sSoks
  5. 怎么移动矩形选框工具选中的东西_程序员应具备的PS基本技能(二):程序员切图最常使用的工具组-选择工具组...
  6. 深度学习中交叉熵_深度计算机视觉,用于检测高熵合金中的钽和铌碎片
  7. SqlServer分组取一瓢和月初月末
  8. Day7 子类调用父类的方法supper 绑定方法与非绑定方法
  9. eclipse build慢问题
  10. java 哈希表和向量_Java基础知识笔记(一:修饰词、向量、哈希表)
  11. 干货 | 140页《深度强化学习入门》
  12. Android做一个WiFi信号测试,Android开发——WiFi信号检测
  13. mac无法验证您网络上的打印机,怎么解决?
  14. 瑞萨单片机c语言程序,瑞萨单片机学习笔记(1)基本配置
  15. js 格式化金额方法
  16. 微信公众号文章采集方案
  17. 电商双十一调查数据分析报告
  18. 风险管理可分为哪两类?具体方法是什么?
  19. 计算机与网络基础知识的问答
  20. 华为NE5000E集群路由器荣获InfoVision奖

热门文章

  1. 考研数据结构之线性表(1.7)——练习题之A和B两个顺序表中相同元素组成一个新的从大到小的有序顺序表C的算法(C表示)
  2. 代理模式——虚拟代理(二)
  3. python运行cmd指令
  4. 分时显示不同图片和问候语
  5. db2设置默认schema_DB2模式schema
  6. android auto 没声音,无法在Android Auto Media App上运行语音命令
  7. 计算机网络可授学位,如何报读在职研究生
  8. 计算机长时间不黑屏怎么设置,当计算机长时间不移动鼠标时,如何设置黑屏?如何将计算机设置为长时间不出现黑屏?...
  9. mie散射 matlab,基于MATLAB与LabVIEW的 Mie散射参数分析系统
  10. 微信小程序获取当前地图坐标,并测量指定地点距离