android登陆注册

来源:互联网 发布:香港阿里云服务器 编辑:程序博客网 时间:2024/05/17 03:18

                                 登陆注册功能是好多软件所必须的功能,实现的流程如下:android客户端提交注册的用户名和密码,然后,将用户名和密码保存到mySql数据库中,登陆的时候从Mysql数据库查询是否已经注册过,如未注册跳到注册界面。

实现的效果如下:

实现的流程图如下:


客户端通过向指定的服务器提交请求和获取返回的参数来确定注册和登陆是否成功

boolean loginValidate = false;// 使用apache HTTP客户端实现String urlStr = "http://10.254.1.233:80/LoginServlet/servlet/RegisterServlet";HttpPost request = new HttpPost(urlStr);// 如果传递参数多的话,可以丢传递的参数进行封装List<NameValuePair> params = new ArrayList<NameValuePair>();// 添加用户名和密码params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("password", password));try {// 设置请求参数项request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));HttpClient client = getHttpClient();// 执行请求返回相应HttpResponse response = client.execute(request);// 判断是否请求成功if (response.getStatusLine().getStatusCode() == 200) {loginValidate = true;// 获得响应信息responseMsg = EntityUtils.toString(response.getEntity());}} catch (Exception e) {e.printStackTrace();}return loginValidate;



需要准备的条件如下:

1.安装好Mysql数据库

2.为Mysql数据库配置驱动jar包,mysql-connector-java-5.1.26-bin.jar 下载地址:点击下载

3.myeclipse和Eclipse开发工具代码编写

4.创建用户表

创建用户表的Sql语句如下:

1.创建数据库兼职         create database jianzhi;         //  drop database jianzhi;2.使用数据库         use jianzhi;3.创建用户表         //创建用户表         create table user(username varchar(30) not null,password varchar(50) not null,primary key(username));         4.插入数据         //插入用户名和密码         insert into user(username,password)values('wangjie','111111');5.查询表中的数据            select * from user;


数据库表创建如下:备注:下图中密码使用MD5进行加密

android客户端代码布局如下:声明以下是模仿赶集网登陆注册布局实现的

1.注册界面的布局实现

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="#ffffffff"    android:orientation="vertical" ><RelativeLayout        android:layout_width="fill_parent"        android:layout_height="48.0dip"        android:background="@drawable/titlebar_center_repeat" >        <ImageView            android:id="@+id/register_back"            android:layout_width="wrap_content"            android:layout_height="35.0dip"            android:layout_centerVertical="true"            android:layout_marginLeft="8.0dip"            android:layout_alignParentLeft="true"            android:background="@drawable/g_green_btn2"            android:gravity="center"            android:paddingLeft="10.0dip"            android:paddingRight="10.0dip"            android:src="@drawable/ic_back"           />        <TextView            android:id="@+id/center_text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:ellipsize="end"            android:gravity="center"            android:singleLine="true"            android:text="注册"            android:textColor="#ffffffff"            android:textSize="18.0dip"            android:textStyle="bold" />           </RelativeLayout>    <ScrollView        android:layout_width="fill_parent"        android:layout_height="fill_parent" >        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:orientation="vertical"            android:padding="10.0dip" >            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:gravity="center"                android:orientation="horizontal" >                <TextView                    android:layout_width="65.0dip"                    android:layout_height="wrap_content"                    android:layout_marginRight="5.0dip"                    android:text="@string/register_username"                    android:textColor="#ff404040"                    android:textSize="16.0dip" />                <RelativeLayout                    android:layout_width="wrap_content"                    android:layout_height="40.0dip" >                    <EditText                        android:id="@+id/user_name_edit"                        android:layout_width="fill_parent"                        android:layout_height="fill_parent"                        android:background="@drawable/item_search_bg"                        android:hint="@string/register_username_hint"                        android:imeOptions="actionNext"                        android:maxLength="20"                        android:paddingLeft="10.0dip"                        android:singleLine="true"                        android:textSize="16.0dip" />                    <ImageView                        android:id="@+id/user_name_clear"                        android:layout_width="wrap_content"                        android:layout_height="fill_parent"                        android:layout_alignParentRight="true"                        android:layout_centerVertical="true"                        android:paddingLeft="5.0dip"                        android:paddingRight="5.0dip"                        android:src="@drawable/close_btn"                        android:visibility="gone" />                </RelativeLayout>            </LinearLayout>            <TextView                android:id="@+id/user_name_error"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:layout_marginLeft="68.0dip"                android:text="用户名为4-20个字符"                android:textColor="#ffff0000"                android:textSize="13.0dip"                android:visibility="gone" />            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="10.0dip"                android:orientation="horizontal" >                <TextView                    android:layout_width="65.0dip"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_marginRight="5.0dip"                    android:text="密        码"                    android:textColor="#ff404040"                    android:textSize="16.0dip" />                <RelativeLayout                    android:layout_width="wrap_content"                    android:layout_height="40.0dip" >                    <EditText                        android:id="@+id/password_edit"                        android:layout_width="fill_parent"                        android:layout_height="fill_parent"                        android:background="@drawable/item_search_bg"                        android:hint="@string/userpassword_rule2"                        android:imeOptions="actionNext"                        android:inputType="textPassword"                        android:maxLength="16"                        android:paddingLeft="10.0dip"                        android:singleLine="true"                        android:textSize="16.0dip" />                    <ImageView                        android:id="@+id/password_clear"                        android:layout_width="wrap_content"                        android:layout_height="fill_parent"                        android:layout_alignParentRight="true"                        android:layout_centerVertical="true"                        android:paddingLeft="5.0dip"                        android:paddingRight="5.0dip"                        android:src="@drawable/close_btn"                        android:visibility="gone" />                </RelativeLayout>            </LinearLayout>            <TextView                android:id="@+id/password_error"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:layout_marginLeft="68.0dip"                android:text="密码至少为6位数"                android:textColor="#ffff0000"                android:textSize="13.0dip"                android:visibility="gone" />            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="10.0dip"                android:orientation="horizontal" >                <TextView                    android:layout_width="65.0dip"                    android:layout_height="wrap_content"                    android:layout_gravity="center"                    android:layout_marginRight="5.0dip"                    android:text="@string/register_password2"                    android:textColor="#ff404040"                    android:textSize="16.0dip" />                <RelativeLayout                    android:layout_width="wrap_content"                    android:layout_height="40.0dip" >                    <EditText                        android:id="@+id/confirm_password_edit"                        android:layout_width="fill_parent"                        android:layout_height="fill_parent"                        android:background="@drawable/item_search_bg"                        android:hint="@string/register_password_hint2"                        android:imeOptions="actionNext"                        android:inputType="textPassword"                        android:maxLength="16"                        android:paddingLeft="10.0dip"                        android:singleLine="true"                        android:textSize="16.0dip" />                    <ImageView                        android:id="@+id/confirm_password_clear"                        android:layout_width="wrap_content"                        android:layout_height="fill_parent"                        android:layout_alignParentRight="true"                        android:layout_centerVertical="true"                        android:paddingLeft="5.0dip"                        android:paddingRight="5.0dip"                        android:src="@drawable/close_btn"                        android:visibility="gone" />                </RelativeLayout>            </LinearLayout>            <TextView                android:id="@+id/confirm_password_error"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:layout_marginLeft="68.0dip"                android:text="您两次输入的密码不一样,请再次输入"                android:textColor="#ffff0000"                android:textSize="13.0dip"                android:visibility="gone" />                                  <Button                android:id="@+id/register_button"                android:layout_width="200.0dip"                android:layout_height="45.0dip"                android:layout_gravity="center_horizontal"                android:layout_marginTop="15dip"                android:background="@drawable/g_green_btn2"                android:text="立即注册"                android:textColor="@color/white"                android:textSize="16.0dip" />        </LinearLayout>    </ScrollView></LinearLayout>


2.登陆界面的布局实现

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="#fffafafa"    android:orientation="vertical" >    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="48.0dip"        android:background="@drawable/titlebar_center_repeat" >        <TextView            android:id="@+id/login_cancle"            android:layout_width="wrap_content"            android:layout_height="35.0dip"            android:layout_alignParentLeft="true"            android:layout_centerVertical="true"            android:layout_marginLeft="8.0dip"            android:background="@drawable/g_green_btn2"            android:gravity="center"            android:paddingLeft="10.0dip"            android:paddingRight="10.0dip"            android:text="取消"            android:textColor="#ffffffff"            android:textSize="14.0dip"            android:textStyle="bold" />        <TextView            android:id="@+id/center_text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:ellipsize="end"            android:gravity="center"            android:singleLine="true"            android:text="登陆账户"            android:textColor="#ffffffff"            android:textSize="18.0dip"            android:textStyle="bold" />        <TextView            android:id="@+id/register_text"            android:layout_width="wrap_content"            android:layout_height="35.0dip"            android:layout_alignParentRight="true"            android:layout_centerVertical="true"            android:layout_marginRight="8.0dip"            android:background="@drawable/g_green_btn2"            android:gravity="center"            android:paddingLeft="10.0dip"            android:paddingRight="10.0dip"            android:text="注册"            android:textColor="#ffffffff"            android:textSize="14.0dip"            android:textStyle="bold" />    </RelativeLayout>    <ScrollView        android:layout_width="fill_parent"        android:layout_height="fill_parent" >        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:orientation="vertical"            android:padding="10.0dip" >            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="5.0dip"                android:gravity="center"                android:orientation="horizontal" >                <TextView                    android:layout_width="58.0dip"                    android:layout_height="wrap_content"                    android:text="账 号"                    android:textColor="#ff404040"                    android:textSize="16.0dip" />                <RelativeLayout                    android:layout_width="fill_parent"                    android:layout_height="40.0dip" >                    <EditText                        android:id="@+id/LoginName"                        android:layout_width="fill_parent"                        android:layout_height="fill_parent"                        android:background="@drawable/item_search_bg"                        android:hint="@string/login_username_hint"                        android:imeOptions="actionNext"                        android:paddingLeft="10.0dip"                        android:paddingRight="30.0dip"                        android:singleLine="true"                        android:textSize="16.0dip" />                    <ImageView                        android:id="@+id/login_name_clear_btn"                        android:layout_width="wrap_content"                        android:layout_height="fill_parent"                        android:layout_alignParentRight="true"                        android:layout_centerVertical="true"                        android:paddingLeft="5.0dip"                        android:paddingRight="5.0dip"                        android:src="@drawable/close_btn"                        android:visibility="gone" />                </RelativeLayout>            </LinearLayout>            <TextView                android:id="@+id/usernameerrorid"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:layout_marginLeft="58.0dip"                android:text="error"                android:textColor="#ffff0000"                android:textSize="13.0dip"                android:visibility="gone" />            <LinearLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="13.0dip"                android:gravity="center"                android:orientation="horizontal" >                <TextView                    android:layout_width="58.0dip"                    android:layout_height="wrap_content"                    android:text="密 码"                    android:textColor="#ff404040"                    android:textSize="16.0dip" />                <RelativeLayout                    android:layout_width="fill_parent"                    android:layout_height="40.0dip" >                    <EditText                        android:id="@+id/password"                        android:layout_width="fill_parent"                        android:layout_height="40.0dip"                        android:background="@drawable/item_search_bg"                        android:hint="@string/login_password_hint"                        android:imeOptions="actionDone"                        android:inputType="textPassword"                        android:maxLength="16"                        android:paddingLeft="10.0dip"                        android:singleLine="true"                        android:textSize="16.0dip" />                    <ImageView                        android:id="@+id/clear_btn2"                        android:layout_width="wrap_content"                        android:layout_height="fill_parent"                        android:layout_alignParentRight="true"                        android:layout_centerVertical="true"                        android:paddingLeft="5.0dip"                        android:paddingRight="5.0dip"                        android:src="@drawable/close_btn"                        android:visibility="gone" />                </RelativeLayout>            </LinearLayout>            <TextView                android:id="@+id/passworderrorid"                android:layout_width="fill_parent"                android:layout_height="fill_parent"                android:layout_marginLeft="58.0dip"                android:text="error"                android:textColor="#ffff0000"                android:textSize="13.0dip"                android:visibility="gone" />            <RelativeLayout                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="13.0dip"                android:orientation="horizontal" >                <LinearLayout                    android:layout_width="wrap_content"                    android:layout_height="fill_parent" >                    <CheckBox                        android:id="@+id/autologin"                        android:layout_width="32.0dip"                        android:layout_height="wrap_content"                        android:layout_marginLeft="5.0dip"                        android:button="@drawable/my_center_check_bg"                        android:checked="true" />                    <TextView                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:text="@string/autologin"                        android:textColor="#ff404040"                        android:textSize="16.0dip" />                </LinearLayout>                <LinearLayout                    android:layout_width="wrap_content"                    android:layout_height="fill_parent"                    android:layout_alignParentRight="true"                    android:layout_centerVertical="true"                    android:layout_marginLeft="5.0dip" >                    <TextView                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:text="忘记密码?"                        android:textColor="@color/gray"                        android:textSize="16.0dip" />                    <TextView                        android:id="@+id/recode_textview"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:text="@string/forgot_pwd"                        android:textColor="@drawable/text_color_green_turn_deep"                        android:textSize="16.0dip" />                </LinearLayout>            </RelativeLayout>            <Button                android:id="@+id/BtnMenulogin"                android:layout_width="200.0dip"                android:layout_height="42.0dip"                android:layout_gravity="center_horizontal"                android:layout_marginBottom="12.0dip"                android:layout_marginTop="12.0dip"                android:background="@drawable/g_green_btn2"                android:text="@string/login"                android:textColor="@color/white"                android:textSize="18.0dip" />        </LinearLayout>    </ScrollView></LinearLayout>

 

1.注册功能客户端的实现

 

package com.jianzhi.activity;import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import com.jianzhi.activity.R.string;import com.util.Encrypt;import com.util.SysApplication;import com.util.Util;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.opengl.Visibility;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;public class Register extends Activity implements OnClickListener {private ImageView register_back, user_name_clear, password_clear,confirm_password_clear;private TextView user_name_error, password_error, confirm_password_error;private Button register_button;private EditText user_name_edit, password_edit, confirm_password_edit;private Dialog registerDialog;private String responseMsg = "";private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟private static final int LOGIN_OK = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.register);SysApplication.getInstance().addActivity(this);InitView();}private void InitView() {// TODO Auto-generated method stubregister_back = (ImageView) findViewById(R.id.register_back);user_name_clear = (ImageView) findViewById(R.id.user_name_clear);password_clear = (ImageView) findViewById(R.id.password_clear);confirm_password_clear = (ImageView) findViewById(R.id.confirm_password_clear);register_button = (Button) findViewById(R.id.register_button);user_name_edit = (EditText) findViewById(R.id.user_name_edit);password_edit = (EditText) findViewById(R.id.password_edit);confirm_password_edit = (EditText) findViewById(R.id.confirm_password_edit);user_name_error = (TextView) findViewById(R.id.user_name_error);password_error = (TextView) findViewById(R.id.password_error);confirm_password_error = (TextView) findViewById(R.id.confirm_password_error);register_back.setOnClickListener(this);register_button.setOnClickListener(this);user_name_edit.setOnClickListener(this);password_edit.setOnClickListener(this);confirm_password_edit.setOnClickListener(this);user_name_clear.setOnClickListener(this);password_clear.setOnClickListener(this);confirm_password_clear.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.register_back:this.finish();break;case R.id.register_button:RegisterUser();break;case R.id.user_name_edit:user_name_error.setVisibility(View.GONE);user_name_clear.setVisibility(View.VISIBLE);password_clear.setVisibility(View.GONE);confirm_password_clear.setVisibility(View.GONE);break;case R.id.password_edit:password_error.setVisibility(View.GONE);user_name_clear.setVisibility(View.GONE);password_clear.setVisibility(View.VISIBLE);confirm_password_clear.setVisibility(View.GONE);break;case R.id.confirm_password_edit:confirm_password_error.setVisibility(View.GONE);user_name_clear.setVisibility(View.GONE);password_clear.setVisibility(View.GONE);confirm_password_clear.setVisibility(View.VISIBLE);break;case R.id.user_name_clear:user_name_edit.setText("");break;case R.id.password_clear:password_edit.setText("");break;case R.id.confirm_password_clear:confirm_password_edit.setText("");break;default:break;}}public void RegisterUser() {if (user_name_edit.getText().toString().trim().equals("")|| user_name_edit.getText().toString().trim().length() > 20|| user_name_edit.getText().toString().trim().length() < 4) {user_name_error.setVisibility(View.VISIBLE);} else if (password_edit.getText().toString().trim().equals("")|| password_edit.getText().toString().trim().length() > 16|| password_edit.getText().toString().trim().length() < 6) {password_error.setVisibility(View.VISIBLE);} else if (!confirm_password_edit.getText().toString().trim().equals(password_edit.getText().toString().trim())) {confirm_password_error.setVisibility(View.VISIBLE);} else {String newusername = user_name_edit.getText().toString();String newpassword = Encrypt.md5(password_edit.getText().toString());String confirmpwd = Encrypt.md5(confirm_password_edit.getText().toString());LinearLayout layout = Util.MyprocessDialog("注册中,请稍后...", this);registerDialog = new Dialog(this, R.style.loading_dialog);// 创建自定义样式dialogregisterDialog.setCancelable(true);// 不可以用“返回键”取消registerDialog.setContentView(layout,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT));// 设置布局registerDialog.show();Thread loginThread = new Thread(new RegisterThread());loginThread.start();}}// 初始化HttpClient,并设置超时public HttpClient getHttpClient() {BasicHttpParams httpParams = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);HttpClient client = new DefaultHttpClient(httpParams);return client;}private boolean registerServer(String username, String password) {boolean loginValidate = false;// 使用apache HTTP客户端实现String urlStr = "http://10.254.1.233:80/LoginServlet/servlet/RegisterServlet";HttpPost request = new HttpPost(urlStr);// 如果传递参数多的话,可以丢传递的参数进行封装List<NameValuePair> params = new ArrayList<NameValuePair>();// 添加用户名和密码params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("password", password));try {// 设置请求参数项request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));HttpClient client = getHttpClient();// 执行请求返回相应HttpResponse response = client.execute(request);// 判断是否请求成功if (response.getStatusLine().getStatusCode() == 200) {loginValidate = true;// 获得响应信息responseMsg = EntityUtils.toString(response.getEntity());}} catch (Exception e) {e.printStackTrace();}return loginValidate;}// HandlerHandler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 0:registerDialog.cancel();Bundle bundle = new Bundle();bundle.putString("username", user_name_edit.getText().toString());bundle.putString("password", password_edit.getText().toString());Intent intent = new Intent();intent.putExtras(bundle);// 返回intentsetResult(RESULT_OK, intent);Register.this.finish();Toast.makeText(Register.this, "注册成功", 1).show();break;case 1:registerDialog.cancel();Toast.makeText(getApplicationContext(), "注册失败",Toast.LENGTH_SHORT).show();break;case 2:registerDialog.cancel();Toast.makeText(getApplicationContext(), "服务器连接失败!",Toast.LENGTH_SHORT).show();break;}}};// RegisterThread线程类class RegisterThread implements Runnable {@Overridepublic void run() {String username = user_name_edit.getText().toString();String password = Encrypt.md5(password_edit.getText().toString());// URL合法,但是这一步并不验证密码是否正确boolean registerValidate = registerServer(username, password);// System.out.println("----------------------------bool is :"+registerValidate+"----------response:"+responseMsg);Message msg = handler.obtainMessage();if (registerValidate) {if (responseMsg.equals("success")) {msg.what = 0;handler.sendMessage(msg);} else {msg.what = 1;handler.sendMessage(msg);}} else {msg.what = 2;handler.sendMessage(msg);}}}}

2.注册界面服务器实现

package com.login;import java.io.IOException;import java.io.PrintWriter;import java.sql.*;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.DB.JdbcConnect;public class RegisterServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Connection conn;PreparedStatement sql;String username = request.getParameter("username");String password = request.getParameter("password");response.setContentType("text/html");response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();String msg = null;if (username != null && password != null) {msg = "success";try {// 加载Mysql驱动conn = JdbcConnect.DbConnect();String insertSql = "insert into user values(?,?)";sql = conn.prepareStatement(insertSql);sql.setString(1, username);sql.setString(2, password);int status = sql.executeUpdate();if (status != 0) {System.out.println("插入数据成功");} else {System.out.println("插入数据失败");}conn.close();} catch (Exception e) {System.out.print(e);}} else {msg = "failed";}out.print(msg);out.flush();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

3.登陆功能客户端的实现

package com.jianzhi.activity;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import com.util.Encrypt;import com.util.SysApplication;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.net.ConnectivityManager;import android.net.NetworkInfo.State;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.provider.Settings;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;public class Login extends Activity implements OnClickListener {private TextView registertextview, login_cancle, recode_textview;private TextView usernameerrorid, passworderrorid;private EditText LoginName, Password;private ImageView login_name_clear_btn, clear_btn2;private CheckBox autologin;private Button BtnMenulogin;private Dialog loadingDialog;// private ProgressDialog mDialog;private String responseMsg = "";private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟private static final int LOGIN_OK = 1;private SharedPreferences sp;int REQUEST_CODE = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.login);SysApplication.getInstance().addActivity(this);sp = getSharedPreferences("userdata", 0);InitView();// 监听记住密码选项autologin.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {if (isChecked) {Editor editor = sp.edit();editor.putString("username", LoginName.getText().toString());editor.putString("password", Password.getText().toString());editor.commit();LoginName.setText(sp.getString("username", ""));Password.setText(sp.getString("password", ""));}}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if (resultCode == REQUEST_CODE || resultCode == RESULT_OK) {Bundle extras = data.getExtras();LoginName.setText(extras.getString("username"));Password.setText(extras.getString("password"));}}private void InitView() {// TODO Auto-generated method stubregistertextview = (TextView) findViewById(R.id.register_text);login_cancle = (TextView) findViewById(R.id.login_cancle);LoginName = (EditText) findViewById(R.id.LoginName);Password = (EditText) findViewById(R.id.password);recode_textview = (TextView) findViewById(R.id.recode_textview);usernameerrorid = (TextView) findViewById(R.id.usernameerrorid);passworderrorid = (TextView) findViewById(R.id.passworderrorid);login_name_clear_btn = (ImageView) findViewById(R.id.login_name_clear_btn);clear_btn2 = (ImageView) findViewById(R.id.clear_btn2);autologin = (CheckBox) findViewById(R.id.autologin);BtnMenulogin = (Button) findViewById(R.id.BtnMenulogin);registertextview.setOnClickListener(this);login_cancle.setOnClickListener(this);LoginName.setOnClickListener(this);Password.setOnClickListener(this);login_name_clear_btn.setOnClickListener(this);clear_btn2.setOnClickListener(this);recode_textview.setOnClickListener(this);BtnMenulogin.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.register_text:Intent intent = new Intent(Login.this, Register.class);startActivityForResult(intent, REQUEST_CODE);break;case R.id.login_cancle:this.finish();break;case R.id.LoginName:usernameerrorid.setVisibility(View.GONE);login_name_clear_btn.setVisibility(View.VISIBLE);clear_btn2.setVisibility(View.GONE);break;case R.id.password:passworderrorid.setVisibility(View.GONE);clear_btn2.setVisibility(View.VISIBLE);login_name_clear_btn.setVisibility(View.GONE);break;case R.id.login_name_clear_btn:LoginName.setText("");passworderrorid.setVisibility(View.GONE);passworderrorid.setVisibility(View.GONE);break;case R.id.clear_btn2:passworderrorid.setVisibility(View.GONE);passworderrorid.setVisibility(View.GONE);Password.setText("");break;case R.id.recode_textview:Toast.makeText(this, "未处理", 1).show();break;case R.id.BtnMenulogin:Loginbtn();break;default:break;}}public void Loginbtn() {if (LoginName.getText().toString().trim().equals("")|| LoginName.getText().toString().trim().length() > 20|| LoginName.getText().toString().trim().length() < 4) {usernameerrorid.setVisibility(View.VISIBLE);usernameerrorid.setText("用户名错误");} else if (Password.getText().toString().trim().equals("")|| Password.getText().toString().trim().length() > 16|| Password.getText().toString().trim().length() < 6) {passworderrorid.setVisibility(View.VISIBLE);passworderrorid.setText("密码错误");} else {LayoutInflater inflater = LayoutInflater.from(this);View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载viewLinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局// main.xml中的ImageViewImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字// 加载动画Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);// 使用ImageView显示动画spaceshipImage.startAnimation(hyperspaceJumpAnimation);tipTextView.setText("登陆中,请稍等...");// 设置加载信息loadingDialog = new Dialog(this, R.style.loading_dialog);// 创建自定义样式dialogloadingDialog.setCancelable(true);// 不可以用“返回键”取消loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT));// 设置布局loadingDialog.show();Thread loginThread = new Thread(new LoginThread());loginThread.start();}}// LoginThread线程类class LoginThread implements Runnable {@Overridepublic void run() {String username = LoginName.getText().toString();String password = Password.getText().toString();boolean checkstatus = sp.getBoolean("checkstatus", false);if (checkstatus) {// 获取已经存在的用户名和密码String realUsername = sp.getString("username", "");String realPassword = sp.getString("password", "");if ((!realUsername.equals("")) && !(realUsername == null)|| (!realPassword.equals(""))|| !(realPassword == null)) {if (username.equals(realUsername)&& password.equals(realPassword)) {username = LoginName.getText().toString();password = Password.getText().toString();}}} else {password = Encrypt.md5(password);}// URL合法,但是这一步并不验证密码是否正确boolean loginValidate = loginServer(username, password);Message msg = handler.obtainMessage();if (loginValidate) {if (responseMsg.equals("success")) {msg.what = 0;handler.sendMessage(msg);} else {msg.what = 1;handler.sendMessage(msg);}} else {msg.what = 2;handler.sendMessage(msg);}}}// HandlerHandler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 0:loadingDialog.cancel();Toast.makeText(getApplicationContext(), "登录成功!",Toast.LENGTH_SHORT).show();Bundle bundle = new Bundle();bundle.putString("username", LoginName.getText().toString());Intent intent = new Intent(Login.this, Tab_check4.class);intent.putExtras(bundle);// 返回intentsetResult(RESULT_OK, intent);Login.this.finish();break;case 1:loadingDialog.cancel();Toast.makeText(getApplicationContext(), "输入的密码错误",Toast.LENGTH_SHORT).show();break;case 2:loadingDialog.cancel();Toast.makeText(getApplicationContext(), "服务器连接失败",Toast.LENGTH_SHORT).show();break;}}};private boolean loginServer(String username, String password) {boolean loginValidate = false;// 使用apache HTTP客户端实现String urlStr = "http://10.254.1.233:80/LoginServlet/servlet/LoginServlet";HttpPost request = new HttpPost(urlStr);// 如果传递参数多的话,可以丢传递的参数进行封装List<NameValuePair> params = new ArrayList<NameValuePair>();// 添加用户名和密码params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("password", password));try {// 设置请求参数项request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));HttpClient client = getHttpClient();// 执行请求返回相应HttpResponse response = client.execute(request);// 判断是否请求成功if (response.getStatusLine().getStatusCode() == 200) {loginValidate = true;// 获得响应信息responseMsg = EntityUtils.toString(response.getEntity());}} catch (Exception e) {e.printStackTrace();}return loginValidate;}// // 初始化HttpClient,并设置超时public HttpClient getHttpClient() {BasicHttpParams httpParams = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);HttpClient client = new DefaultHttpClient(httpParams);return client;}}


4.登陆功能服务器实现

package com.login;import java.io.IOException;import java.io.PrintWriter;import java.sql.*;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.DB.JdbcConnect;public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Connection conn;PreparedStatement sql;ResultSet rs;String username = request.getParameter("username");String password = request.getParameter("password");response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();String msg = null;String selectsql = "select username,password from user where username=? and password=?";try {conn = JdbcConnect.DbConnect();sql = conn.prepareStatement(selectsql);if (username != null && password != null) {sql.setString(1, username);sql.setString(2, password);rs = sql.executeQuery();boolean bool = rs.next();if (bool == true) {msg = "success";} else {msg = "failed";}} else {msg = "failed";}conn.close();} catch (Exception e) {System.out.print(e);}out.print(msg);out.flush();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

5.服务器用的的连接mysql驱动的使用方法是

package com.DB;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class JdbcConnect {public static Connection DbConnect() {Connection conn;String driver = "com.mysql.jdbc.Driver";String name = "root";String password = "123456";try {Class.forName(driver).newInstance();String url = "jdbc:mysql://localhost/jianzhi";conn = DriverManager.getConnection(url, name, password);return conn;} catch (Exception e) {System.out.println(e);return null;}}public static void DBClose(Connection conn) throws SQLException {conn.close();}}


6.用户密码用到的MD5加密的方法类如下:

package com.util;import java.security.MessageDigest;public class Encrypt {public static String md5(String str) {MessageDigest md5 = null;try {md5 = MessageDigest.getInstance("MD5");} catch (Exception e) {e.printStackTrace();return "";}char[] charArray = str.toCharArray();byte[] byteArray = new byte[charArray.length];for (int i = 0; i < charArray.length; i++) {byteArray[i] = (byte) charArray[i];}byte[] md5Bytes = md5.digest(byteArray);StringBuffer hexValue = new StringBuffer();for (int i = 0; i < md5Bytes.length; i++) {int val = ((int) md5Bytes[i]) & 0xff;if (val < 16) {hexValue.append("0");}hexValue.append(Integer.toHexString(val));}return hexValue.toString();}}



 

原创粉丝点击