Android QQ登录验证的小例子

客户端:

1、登录时检查网络状态

2、登录加载进度条

3、登录服务器端进行验证,如果用户名和密码存在且正确,则登录,否则失败

4、注册时将用户信息保存到服务器端数据库中(MySQL)

5、记住密码功能(还不完善,只是测试)

6、对密码信息进行md5()单向加密

服务器端:

1、接收客户端发来的登录请求,如果用户名和密码存在于MySQL数据库中则返回客户端一个响应信息"success"

2、接收客户端发来的注册请求,将用户名和密码存放到MySQL数据库中

不过目前还存在很多问题,以后有时间继续更新

下面是效果图:

完整代码下载:http://115.com/file/bexv3qlf#LoginDemo.zip

客户端代码:

登录代码:这里是使用HttpClient来进行与服务器端的交互的,密码加密部分只是简单的用了下md5(),如果正式的项目中可以选用非对称加密算法会更加安全

  1. package com.loulijun.logindemo;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.message.BasicNameValuePair;  
  14. import org.apache.http.params.BasicHttpParams;  
  15. import org.apache.http.params.HttpConnectionParams;  
  16. import org.apache.http.protocol.HTTP;  
  17. import org.apache.http.util.EntityUtils;  
  18.   
  19. import android.app.Activity;  
  20. import android.app.AlertDialog;  
  21. import android.app.ProgressDialog;  
  22. import android.content.Context;  
  23. import android.content.DialogInterface;  
  24. import android.content.Intent;  
  25. import android.content.SharedPreferences;  
  26. import android.content.SharedPreferences.Editor;  
  27. import android.net.ConnectivityManager;  
  28. import android.net.NetworkInfo.State;  
  29. import android.os.Bundle;  
  30. import android.os.Handler;  
  31. import android.os.Message;  
  32. import android.provider.Settings;  
  33. import android.view.View;  
  34. import android.widget.Button;  
  35. import android.widget.CheckBox;  
  36. import android.widget.CompoundButton;  
  37. import android.widget.EditText;  
  38. import android.widget.Toast;  
  39.   
  40. public class LoginDemoActivity extends Activity {  
  41.     /** Called when the activity is first created. */  
  42.     private Button loginBtn;  
  43.     private Button registerBtn;  
  44.     private EditText inputUsername;  
  45.     private EditText inputPassword;  
  46.     private CheckBox saveInfoItem;  
  47.     private ProgressDialog mDialog;  
  48.     private String responseMsg = "";  
  49.     private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟    
  50.     private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟    
  51.     private static final int LOGIN_OK = 1;  
  52.     private SharedPreferences sp;  
  53.       
  54.   
  55.     @Override  
  56.     public void onCreate(Bundle savedInstanceState) {  
  57.         super.onCreate(savedInstanceState);  
  58.         setContentView(R.layout.login);  
  59.         loginBtn = (Button)findViewById(R.id.login_btn_login);  
  60.         registerBtn = (Button)findViewById(R.id.login_btn_zhuce);  
  61.         inputUsername = (EditText)findViewById(R.id.login_edit_account);  
  62.         inputPassword = (EditText)findViewById(R.id.login_edit_pwd);  
  63.         saveInfoItem = (CheckBox)findViewById(R.id.login_cb_savepwd);  
  64.           
  65.         sp = getSharedPreferences("userdata",0);  
  66.         //初始化数据  
  67.         LoadUserdata();  
  68.   
  69.         //检查网络  
  70.         CheckNetworkState();  
  71.   
  72.         //监听记住密码选项  
  73.         saveInfoItem.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener()    
  74.         {    
  75.             @Override    
  76.             public void onCheckedChanged(CompoundButton buttonView,    
  77.                     boolean isChecked) {    
  78.                 // TODO Auto-generated method stub    
  79.                 //载入用户信息  
  80.                  
  81.                 Editor editor = sp.edit();  
  82.                   
  83.                 if(saveInfoItem.isChecked())  
  84.                 {  
  85.                      //获取已经存在的用户名和密码  
  86.                     String realUsername = sp.getString("username""");  
  87.                     String realPassword = sp.getString("password""");  
  88.                     editor.putBoolean("checkstatus"true);  
  89.                     editor.commit();  
  90.                        
  91.                      if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))  
  92.                      {  
  93.                         //清空输入框  
  94.                         inputUsername.setText("");  
  95.                           inputPassword.setText("");  
  96.                           //设置已有值  
  97.                          inputUsername.setText(realUsername);  
  98.                          inputPassword.setText(realPassword);  
  99.                      }  
  100.                 }else  
  101.                 {  
  102.                     editor.putBoolean("checkstatus"false);  
  103.                     editor.commit();  
  104.                     //清空输入框  
  105.                     inputUsername.setText("");  
  106.                      inputPassword.setText("");  
  107.                 }  
  108.                  
  109.             }    
  110.                 
  111.         });    
  112.         //登录  
  113.         loginBtn.setOnClickListener(new Button.OnClickListener()  
  114.         {  
  115.   
  116.             @Override  
  117.             public void onClick(View arg0) {  
  118.                 mDialog = new ProgressDialog(LoginDemoActivity.this);  
  119.                 mDialog.setTitle("登陆");  
  120.                 mDialog.setMessage("正在登陆服务器,请稍后...");  
  121.                 mDialog.show();  
  122.                 Thread loginThread = new Thread(new LoginThread());  
  123.                   
  124.                 loginThread.start();  
  125.   
  126.             }  
  127.               
  128.         });  
  129.           
  130.         registerBtn.setOnClickListener(new Button.OnClickListener()  
  131.         {  
  132.   
  133.             @Override  
  134.             public void onClick(View arg0) {  
  135.                 Intent intent = new Intent();  
  136.                 intent.setClass(LoginDemoActivity.this, RegisterActivity.class);  
  137.                 startActivity(intent);  
  138.             }  
  139.               
  140.         });  
  141.     }  
  142.       
  143.       
  144.     private boolean loginServer(String username, String password)  
  145.     {  
  146.         boolean loginValidate = false;  
  147.         //使用apache HTTP客户端实现  
  148.         String urlStr = "http://192.168.1.101:8080/LoginServlet/LoginServlet";  
  149.         HttpPost request = new HttpPost(urlStr);  
  150.         //如果传递参数多的话,可以丢传递的参数进行封装  
  151.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  152.         //添加用户名和密码  
  153.         params.add(new BasicNameValuePair("username",username));  
  154.         params.add(new BasicNameValuePair("password",password));  
  155.         try  
  156.         {  
  157.             //设置请求参数项  
  158.             request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  159.             HttpClient client = getHttpClient();  
  160.             //执行请求返回相应  
  161.             HttpResponse response = client.execute(request);  
  162.               
  163.             //判断是否请求成功  
  164.             if(response.getStatusLine().getStatusCode()==200)  
  165.             {  
  166.                 loginValidate = true;  
  167.                 //获得响应信息  
  168.                 responseMsg = EntityUtils.toString(response.getEntity());  
  169.             }  
  170.         }catch(Exception e)  
  171.         {  
  172.             e.printStackTrace();  
  173.         }  
  174.         return loginValidate;  
  175.     }  
  176.       
  177.      
  178.       
  179.     //初始化HttpClient,并设置超时  
  180.     public HttpClient getHttpClient()  
  181.     {  
  182.         BasicHttpParams httpParams = new BasicHttpParams();  
  183.         HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
  184.         HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
  185.         HttpClient client = new DefaultHttpClient(httpParams);  
  186.         return client;  
  187.     }  
  188.   
  189.       
  190.     //判断是否记住密码,默认记住  
  191.     private boolean isRemembered() {  
  192.         try {  
  193.             if (saveInfoItem.isChecked()) {  
  194.                 return true;  
  195.             }  
  196.         } catch (Exception e) {  
  197.             // TODO Auto-generated catch block  
  198.             e.printStackTrace();  
  199.         }  
  200.         return false;  
  201.     }  
  202.     //初始化用户数据  
  203.     private void LoadUserdata()  
  204.     {  
  205.         boolean checkstatus = sp.getBoolean("checkstatus"false);  
  206.         if(checkstatus)  
  207.         {  
  208.             saveInfoItem.setChecked(true);  
  209.             //载入用户信息  
  210.              //获取已经存在的用户名和密码  
  211.             String realUsername = sp.getString("username""");  
  212.             String realPassword = sp.getString("password""");  
  213.             if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))  
  214.             {  
  215.                 inputUsername.setText("");  
  216.                 inputPassword.setText("");  
  217.                 inputUsername.setText(realUsername);  
  218.                 inputPassword.setText(realPassword);  
  219.             }      
  220.         }else  
  221.         {  
  222.             saveInfoItem.setChecked(false);  
  223.             inputUsername.setText("");  
  224.             inputPassword.setText("");  
  225.         }  
  226.           
  227.     }  
  228.     //检查网络状态  
  229.     public void CheckNetworkState()  
  230.     {  
  231.         boolean flag = false;  
  232.         ConnectivityManager manager = (ConnectivityManager)getSystemService(  
  233.                 Context.CONNECTIVITY_SERVICE);  
  234.         State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
  235.         State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  
  236.         //如果3G、wifi、2G等网络状态是连接的,则退出,否则显示提示信息进入网络设置界面  
  237.         if(mobile == State.CONNECTED||mobile==State.CONNECTING)  
  238.         return;  
  239.         if(wifi == State.CONNECTED||wifi==State.CONNECTING)  
  240.         return;  
  241.         showTips();  
  242.     }  
  243.       
  244.     private void showTips()  
  245.     {  
  246.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  247.         builder.setIcon(android.R.drawable.ic_dialog_alert);  
  248.         builder.setTitle("没有可用网络");  
  249.         builder.setMessage("当前网络不可用,是否设置网络?");  
  250.         builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  251.               
  252.             @Override  
  253.             public void onClick(DialogInterface dialog, int which) {  
  254.                 // 如果没有网络连接,则进入网络设置界面  
  255.                 startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));  
  256.             }  
  257.         });  
  258.         builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  259.               
  260.             @Override  
  261.             public void onClick(DialogInterface dialog, int which) {  
  262.                 dialog.cancel();  
  263.                 LoginDemoActivity.this.finish();  
  264.             }  
  265.         });  
  266.         builder.create();  
  267.         builder.show();  
  268.     }  
  269.     //Handler  
  270.     Handler handler = new Handler()  
  271.     {  
  272.         public void handleMessage(Message msg)  
  273.         {  
  274.             switch(msg.what)  
  275.             {  
  276.             case 0:  
  277.                 mDialog.cancel();  
  278.   
  279.                 Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();  
  280.                 Intent intent = new Intent();  
  281.                 intent.setClass(LoginDemoActivity.this, MainActivity.class);  
  282.                 startActivity(intent);  
  283.                 finish();  
  284.                 break;  
  285.             case 1:  
  286.                 mDialog.cancel();  
  287.                 Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();  
  288.                 break;  
  289.             case 2:  
  290.                 mDialog.cancel();  
  291.                 Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();  
  292.                 break;  
  293.               
  294.             }  
  295.               
  296.         }  
  297.     };  
  298.       
  299.     //LoginThread线程类  
  300.     class LoginThread implements Runnable  
  301.     {  
  302.   
  303.         @Override  
  304.         public void run() {  
  305.             String username = inputUsername.getText().toString();  
  306.             String password = inputPassword.getText().toString();      
  307.             boolean checkstatus = sp.getBoolean("checkstatus"false);  
  308.             if(checkstatus)  
  309.             {  
  310.                  //获取已经存在的用户名和密码  
  311.                 String realUsername = sp.getString("username""");  
  312.                 String realPassword = sp.getString("password""");  
  313.                 if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))  
  314.                 {  
  315.                     if(username.equals(realUsername)&&password.equals(realPassword))  
  316.                     {  
  317.                         username = inputUsername.getText().toString();  
  318.                         password = inputPassword.getText().toString();  
  319.                     }  
  320.                 }  
  321.             }else  
  322.             {  
  323.                 password = md5(password);  
  324.             }  
  325.             System.out.println("username="+username+":password="+password);  
  326.                   
  327.             //URL合法,但是这一步并不验证密码是否正确  
  328.             boolean loginValidate = loginServer(username, password);  
  329.             System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg);  
  330.             Message msg = handler.obtainMessage();  
  331.             if(loginValidate)  
  332.             {  
  333.                 if(responseMsg.equals("success"))  
  334.                 {  
  335.                     msg.what = 0;  
  336.                     handler.sendMessage(msg);  
  337.                 }else  
  338.                 {  
  339.                     msg.what = 1;  
  340.                     handler.sendMessage(msg);  
  341.                 }  
  342.                   
  343.             }else  
  344.             {  
  345.                 msg.what = 2;  
  346.                 handler.sendMessage(msg);  
  347.             }  
  348.         }  
  349.           
  350.     }  
  351.       
  352.       
  353.     /** 
  354.      * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全   
  355.      * @param str 
  356.      * @return 
  357.      */  
  358.     public static String md5(String str)    
  359.     {    
  360.         MessageDigest md5 = null;    
  361.         try    
  362.         {    
  363.             md5 = MessageDigest.getInstance("MD5");    
  364.         }catch(Exception e)    
  365.         {    
  366.             e.printStackTrace();    
  367.             return "";    
  368.         }    
  369.             
  370.         char[] charArray = str.toCharArray();    
  371.         byte[] byteArray = new byte[charArray.length];    
  372.             
  373.         for(int i = 0; i < charArray.length; i++)    
  374.         {    
  375.             byteArray[i] = (byte)charArray[i];    
  376.         }    
  377.         byte[] md5Bytes = md5.digest(byteArray);    
  378.             
  379.         StringBuffer hexValue = new StringBuffer();    
  380.         forint i = 0; i < md5Bytes.length; i++)    
  381.         {    
  382.             int val = ((int)md5Bytes[i])&0xff;    
  383.             if(val < 16)    
  384.             {    
  385.                 hexValue.append("0");    
  386.             }    
  387.             hexValue.append(Integer.toHexString(val));    
  388.         }    
  389.         return hexValue.toString();    
  390.     }    
  391.      
  392.       
  393. }  

注册代码

  1. package com.loulijun.logindemo;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.message.BasicNameValuePair;  
  14. import org.apache.http.params.BasicHttpParams;  
  15. import org.apache.http.params.HttpConnectionParams;  
  16. import org.apache.http.protocol.HTTP;  
  17. import org.apache.http.util.EntityUtils;  
  18.   
  19. import com.loulijun.logindemo.LoginDemoActivity.LoginThread;  
  20.   
  21. import android.app.Activity;  
  22. import android.app.AlertDialog;  
  23. import android.app.ProgressDialog;  
  24. import android.content.DialogInterface;  
  25. import android.content.Intent;  
  26. import android.content.SharedPreferences;  
  27. import android.content.SharedPreferences.Editor;  
  28. import android.os.Bundle;  
  29. import android.os.Handler;  
  30. import android.os.Message;  
  31. import android.util.Log;  
  32. import android.view.View;  
  33. import android.widget.Button;  
  34. import android.widget.EditText;  
  35. import android.widget.Toast;  
  36.   
  37. public class RegisterActivity extends Activity {  
  38.     private EditText newUser,newPassword,confirmPassword;  
  39.     private Button registerBtn, clearBtn;  
  40.     private ProgressDialog mDialog;  
  41.     private String responseMsg = "";  
  42.     private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟    
  43.     private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟    
  44.     private static final int LOGIN_OK = 1;  
  45.     @Override  
  46.     protected void onCreate(Bundle savedInstanceState) {  
  47.         // TODO Auto-generated method stub  
  48.         super.onCreate(savedInstanceState);  
  49.         setContentView(R.layout.register);  
  50.         newUser = (EditText)findViewById(R.id.newUser_input);  
  51.         newPassword = (EditText)findViewById(R.id.newPassword_input);  
  52.         confirmPassword = (EditText)findViewById(R.id.Confirm_input);  
  53.         registerBtn = (Button)findViewById(R.id.registerbtn);  
  54.         clearBtn = (Button)findViewById(R.id.clearbtn);  
  55.         registerBtn.setOnClickListener(new Button.OnClickListener()  
  56.         {  
  57.   
  58.             @Override  
  59.             public void onClick(View v) {  
  60.                 String newusername = newUser.getText().toString();  
  61.                 String newpassword = md5(newPassword.getText().toString());  
  62.                 String confirmpwd = md5(confirmPassword.getText().toString());  
  63.                   
  64.                 if(newpassword.equals(confirmpwd))  
  65.                 {  
  66.                     SharedPreferences sp = getSharedPreferences("userdata",0);  
  67.                     Editor editor = sp.edit();  
  68.                     editor.putString("username", newusername);  
  69.                     editor.putString("password", newpassword);  
  70.                     editor.commit();  
  71.                     mDialog = new ProgressDialog(RegisterActivity.this);  
  72.                     mDialog.setTitle("登陆");  
  73.                     mDialog.setMessage("正在登陆服务器,请稍后...");  
  74.                     mDialog.show();  
  75.                     Thread loginThread = new Thread(new RegisterThread());  
  76.                     loginThread.start();  
  77.                       
  78.                 }else  
  79.                 {  
  80.                     Toast.makeText(getApplicationContext(), "您两次输入的密码不一致!", Toast.LENGTH_SHORT).show();  
  81.                 }  
  82.             }  
  83.               
  84.         });  
  85.           
  86.         clearBtn.setOnClickListener(new Button.OnClickListener()  
  87.         {  
  88.   
  89.             @Override  
  90.             public void onClick(View v) {  
  91.                 newUser.setText("");  
  92.                 newPassword.setText("");  
  93.                 confirmPassword.setText("");  
  94.             }  
  95.               
  96.         });  
  97.     }  
  98.       
  99.     //初始化HttpClient,并设置超时  
  100.     public HttpClient getHttpClient()  
  101.     {  
  102.         BasicHttpParams httpParams = new BasicHttpParams();  
  103.         HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
  104.         HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
  105.         HttpClient client = new DefaultHttpClient(httpParams);  
  106.         return client;  
  107.     }  
  108.       
  109.      private boolean registerServer(String username, String password)  
  110.         {  
  111.             boolean loginValidate = false;  
  112.             //使用apache HTTP客户端实现  
  113.             String urlStr = "http://192.168.1.101:8080/LoginServlet/RegisterServlet";  
  114.             HttpPost request = new HttpPost(urlStr);  
  115.             //如果传递参数多的话,可以丢传递的参数进行封装  
  116.             List<NameValuePair> params = new ArrayList<NameValuePair>();  
  117.             //添加用户名和密码  
  118.             params.add(new BasicNameValuePair("username",username));  
  119.             params.add(new BasicNameValuePair("password",password));  
  120.             try  
  121.             {  
  122.                 //设置请求参数项  
  123.                 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  124.                 HttpClient client = getHttpClient();  
  125.                 //执行请求返回相应  
  126.                 HttpResponse response = client.execute(request);  
  127.                   
  128.                 //判断是否请求成功  
  129.                 if(response.getStatusLine().getStatusCode()==200)  
  130.                 {  
  131.                     loginValidate = true;  
  132.                     //获得响应信息  
  133.                     responseMsg = EntityUtils.toString(response.getEntity());  
  134.                 }  
  135.             }catch(Exception e)  
  136.             {  
  137.                 e.printStackTrace();  
  138.             }  
  139.             return loginValidate;  
  140.         }  
  141.        
  142.     //Handler  
  143.         Handler handler = new Handler()  
  144.         {  
  145.             public void handleMessage(Message msg)  
  146.             {  
  147.                 switch(msg.what)  
  148.                 {  
  149.                 case 0:  
  150.                     mDialog.cancel();  
  151.                     showDialog("注册成功!");  
  152.                     break;  
  153.                 case 1:  
  154.                     mDialog.cancel();  
  155.                     Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show();  
  156.                     break;  
  157.                 case 2:  
  158.                     mDialog.cancel();  
  159.                     Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();  
  160.                     break;  
  161.                   
  162.                 }  
  163.                   
  164.             }  
  165.         };  
  166.           
  167.           
  168.         //RegisterThread线程类  
  169.         class RegisterThread implements Runnable  
  170.         {  
  171.   
  172.             @Override  
  173.             public void run() {  
  174.                 String username = newUser.getText().toString();  
  175.                 String password = md5(newPassword.getText().toString());  
  176.                       
  177.                 //URL合法,但是这一步并不验证密码是否正确  
  178.                 boolean registerValidate = registerServer(username, password);  
  179.                 //System.out.println("----------------------------bool is :"+registerValidate+"----------response:"+responseMsg);  
  180.                 Message msg = handler.obtainMessage();  
  181.                 if(registerValidate)  
  182.                 {  
  183.                     if(responseMsg.equals("success"))  
  184.                     {  
  185.                         msg.what = 0;  
  186.                         handler.sendMessage(msg);  
  187.                     }else  
  188.                     {  
  189.                         msg.what = 1;  
  190.                         handler.sendMessage(msg);  
  191.                     }  
  192.                       
  193.                 }else  
  194.                 {  
  195.                     msg.what = 2;  
  196.                     handler.sendMessage(msg);  
  197.                 }  
  198.             }  
  199.               
  200.         }  
  201.       
  202.     private void showDialog(String str)  
  203.     {  
  204.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  205.         builder.setTitle("注册");  
  206.         builder.setMessage(str);  
  207.         builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  208.               
  209.             @Override  
  210.             public void onClick(DialogInterface dialog, int which) {  
  211.                 dialog.dismiss();  
  212.                 Intent intent = new Intent();  
  213.                 intent.setClass(RegisterActivity.this, LoginDemoActivity.class);  
  214.                 startActivity(intent);  
  215.                 finish();  
  216.             }  
  217.         });  
  218.         AlertDialog dialog = builder.create();  
  219.         dialog.show();  
  220.     }  
  221.       
  222.     /** 
  223.      * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全   
  224.      * @param str 
  225.      * @return 
  226.      */  
  227.     public static String md5(String str)    
  228.     {    
  229.         MessageDigest md5 = null;    
  230.         try    
  231.         {    
  232.             md5 = MessageDigest.getInstance("MD5");    
  233.         }catch(Exception e)    
  234.         {    
  235.             e.printStackTrace();    
  236.             return "";    
  237.         }    
  238.             
  239.         char[] charArray = str.toCharArray();    
  240.         byte[] byteArray = new byte[charArray.length];    
  241.             
  242.         for(int i = 0; i < charArray.length; i++)    
  243.         {    
  244.             byteArray[i] = (byte)charArray[i];    
  245.         }    
  246.         byte[] md5Bytes = md5.digest(byteArray);    
  247.             
  248.         StringBuffer hexValue = new StringBuffer();    
  249.         forint i = 0; i < md5Bytes.length; i++)    
  250.         {    
  251.             int val = ((int)md5Bytes[i])&0xff;    
  252.             if(val < 16)    
  253.             {    
  254.                 hexValue.append("0");    
  255.             }    
  256.             hexValue.append(Integer.toHexString(val));    
  257.         }    
  258.         return hexValue.toString();    
  259.     }    
  260.         
  261. }  

主界面的布局:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@+id/loginRoot"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <LinearLayout   
  9.         android:id="@+id/linear1"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:layout_weight="1"  
  13.         android:background="@drawable/default_bg"  
  14.         android:orientation="vertical"  
  15.         >  
  16.         <RelativeLayout   
  17.             android:id="@+id/relativelayout2"  
  18.             android:layout_width="fill_parent"  
  19.             android:layout_height="wrap_content"  
  20.             android:layout_marginLeft="15.0px"  
  21.             android:layout_marginRight="15.0px"  
  22.             android:layout_marginTop="62.0px"  
  23.             android:background="@drawable/login_back"  
  24.             android:paddingBottom="10.0px"  
  25.             android:paddingTop="21.0px"  
  26.             >  
  27.             <ImageView  
  28.                 android:id="@+id/faceImg"  
  29.                 android:layout_width="wrap_content"  
  30.                 android:layout_height="wrap_content"  
  31.                 android:background="@drawable/login_head"  
  32.                 />  
  33.             <EditText  
  34.                 android:id="@+id/login_edit_account"  
  35.                 android:layout_width="fill_parent"  
  36.                 android:layout_height="wrap_content"  
  37.                 android:layout_alignParentTop="true"  
  38.                 android:layout_marginBottom="5.0dip"  
  39.                 android:layout_marginLeft="5.0dip"  
  40.                 android:layout_marginTop="5.0dip"  
  41.                 android:layout_marginRight="5.0dip"  
  42.                 android:layout_toRightOf="@+id/faceImg"  
  43.                 android:background="@drawable/edit_login"  
  44.                 android:hint="@string/username_hint"  
  45.                 android:singleLine="true"  
  46.                 android:paddingLeft="45.0sp"  
  47.                 android:saveEnabled="true"  
  48.                 android:textColor="#ff3f3f3f"  
  49.                 />  
  50.             <TextView   
  51.                 android:id="@+id/textview01"  
  52.                 android:layout_width="wrap_content"  
  53.                 android:layout_height="wrap_content"  
  54.                 android:layout_alignBottom="@+id/login_edit_account"  
  55.                 android:layout_alignLeft="@+id/login_edit_account"  
  56.                 android:layout_alignTop="@+id/login_edit_account"  
  57.                 android:layout_marginRight="15.0sp"  
  58.                 android:gravity="center_vertical"  
  59.                 android:paddingLeft="7.0sp"  
  60.                 android:text="@string/username_input"  
  61.                 android:textColor="#ff3f3f3f"  
  62.                 android:textSize="16.0dip"  
  63.                 />  
  64.             <ImageButton   
  65.                 android:id="@+id/usernamespinner"  
  66.                 android:layout_width="wrap_content"  
  67.                 android:layout_height="wrap_content"  
  68.                 android:layout_alignBottom="@+id/login_edit_account"  
  69.                 android:layout_alignRight="@+id/login_edit_account"  
  70.                 android:layout_alignTop="@+id/login_edit_account"  
  71.                 android:layout_marginRight="1.0dip"  
  72.                 android:background="@drawable/more_select"  
  73.                 />  
  74.               
  75.             <EditText  
  76.                 android:id="@+id/login_edit_pwd"  
  77.                 android:layout_width="wrap_content"  
  78.                 android:layout_height="wrap_content"  
  79.                 android:layout_alignLeft="@+id/login_edit_account"  
  80.                 android:layout_alignRight="@+id/login_edit_account"  
  81.                 android:layout_below="@+id/login_edit_account"  
  82.                 android:layout_marginRight="1.0dip"  
  83.                 android:background="@drawable/edit_login"  
  84.                 android:password="true"  
  85.                 android:singleLine="true"  
  86.                 android:paddingLeft="45.0sp"  
  87.                 android:saveEnabled="true"  
  88.                 android:hint="@string/password_hint"  
  89.                 />  
  90.             <TextView   
  91.                 android:id="@+id/textview02"  
  92.                 android:layout_width="wrap_content"  
  93.                 android:layout_height="wrap_content"  
  94.                 android:layout_alignBottom="@+id/login_edit_pwd"  
  95.                 android:layout_alignRight="@+id/textview01"  
  96.                 android:layout_alignTop="@+id/login_edit_pwd"  
  97.                 android:gravity="center_vertical"  
  98.                 android:paddingLeft="7.0sp"  
  99.                 android:text="@string/password_input"  
  100.                 android:textColor="#ff3f3f3f"  
  101.                 android:textSize="16.0dip"                  
  102.                 />  
  103.             <CheckBox   
  104.                 android:id="@+id/login_cb_savepwd"  
  105.                 android:layout_width="wrap_content"  
  106.                 android:layout_height="wrap_content"  
  107.                 android:layout_alignBaseline="@+id/login_btn_login"  
  108.                 android:button="@drawable/btn_check"  
  109.                 android:paddingLeft="39.0px"  
  110.                 android:text="@string/opt_remember"  
  111.                 android:textColor="#ff222222"  
  112.                 android:textSize="16.0sp"  
  113.                 />  
  114.             <Button  
  115.                 android:id="@+id/login_btn_login"  
  116.                 android:layout_width="90.0dp"  
  117.                 android:layout_height="wrap_content"  
  118.                 android:layout_below="@+id/textview02"  
  119.                 android:layout_toLeftOf="@+id/login_btn_zhuce"  
  120.                 android:layout_marginTop="7.0px"  
  121.                 android:text="@string/login" />  
  122.             <Button  
  123.                 android:id="@+id/login_btn_zhuce"  
  124.                 android:layout_width="90.0dp"  
  125.                 android:layout_height="wrap_content"  
  126.                 android:layout_alignParentRight="true"  
  127.                 android:layout_below="@+id/textview02"  
  128.                 android:layout_marginTop="7.0px"  
  129.                 android:text="@string/zhuce" />  
  130.         </RelativeLayout>  
  131.     </LinearLayout>  
  132.   
  133. </LinearLayout>  

服务器端:

服务器端采用的是Servlet,比较简单

需要创建一个表,MySQL的,这部分还没有放到代码中处理,数据库名:monitordb,表:username varchar(30),password(50)。注意配置一下MySQL的驱动

web.xml

  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  4.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  6.    version="2.5">   
  7.   
  8.   
  9.   <servlet>  
  10.     <servlet-name>LoginServlet</servlet-name>  
  11.     <servlet-class>com.loulijun.login.LoginServlet</servlet-class>  
  12.   </servlet>  
  13.    
  14.   <!-- Define the Manager Servlet Mapping -->  
  15.   <servlet-mapping>  
  16.     <servlet-name>LoginServlet</servlet-name>  
  17.     <url-pattern>/LoginServlet</url-pattern>  
  18.   </servlet-mapping>  
  19.   
  20.     <servlet>  
  21.     <servlet-name>RegisterServlet</servlet-name>  
  22.     <servlet-class>com.loulijun.login.RegisterServlet</servlet-class>  
  23.   </servlet>  
  24.    
  25.   <!-- Define the Manager Servlet Mapping -->  
  26.   <servlet-mapping>  
  27.     <servlet-name>RegisterServlet</servlet-name>  
  28.     <url-pattern>/RegisterServlet</url-pattern>  
  29.   </servlet-mapping>  
  30.    
  31. </web-app>  

LoginServlet.java:用于登录信息的Servlet
  1. package com.loulijun.login;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.sql.*;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. public class LoginServlet extends HttpServlet  
  13. {  
  14.     public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  
  15.     {  
  16.           
  17.         Connection conn;  
  18.         PreparedStatement sql;  
  19.         ResultSet rs;  
  20.         try  
  21.         {  
  22.             Class.forName("com.mysql.jdbc.Driver");  
  23.         }  
  24.         catch (Exception e)  
  25.         {  
  26.             System.out.print(e);  
  27.         }  
  28.   
  29.         String username = request.getParameter("username");  
  30.         String password = request.getParameter("password");  
  31.         response.setContentType("text/html");  
  32.         response.setCharacterEncoding("utf-8");  
  33.         PrintWriter out = response.getWriter();  
  34.         String msg = null;  
  35.         String uri = "jdbc:mysql://127.0.0.1/monitordb";  
  36.         String selectsql = "select username,password from user where username=? and password=?";  
  37.           
  38.         try  
  39.         {  
  40.             conn = DriverManager.getConnection(uri, "root""loulijun");  
  41.             sql = conn.prepareStatement(selectsql);  
  42.   
  43.             if(username!=null&&password!=null)  
  44.             {  
  45.                 sql.setString(1,username);  
  46.                 sql.setString(2,password);  
  47.                 rs = sql.executeQuery();  
  48.                 boolean bool = rs.next();  
  49.                 if(bool == true)  
  50.                 {  
  51.                     msg = "success";  
  52.                 }else  
  53.                 {  
  54.                     msg = "failed";  
  55.                 }  
  56.             }else  
  57.             {  
  58.                 msg = "failed";  
  59.             }  
  60.               
  61.             conn.close();  
  62.         }  
  63.         catch (SQLException e)  
  64.         {  
  65.             System.out.print(e);  
  66.         }  
  67.         out.print(msg);  
  68.         out.flush();  
  69.         out.close();  
  70.     }  
  71.   
  72.     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException  
  73.     {  
  74.         doGet(request, response);  
  75.     }  
  76.   
  77. }  

RegisterServlet.java:用于处理注册信息的Servlet

  1. package com.loulijun.login;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.sql.*;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. public class RegisterServlet extends HttpServlet  
  13. {  
  14.     public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  
  15.     {  
  16.         Connection conn;  
  17.         PreparedStatement sql;  
  18.         try  
  19.         {  
  20.             Class.forName("com.mysql.jdbc.Driver");  
  21.         }  
  22.         catch (Exception e)  
  23.         {  
  24.             System.out.print(e);  
  25.         }  
  26.   
  27.         String username = request.getParameter("username");  
  28.         String password = request.getParameter("password");  
  29.         response.setContentType("text/html");  
  30.         response.setCharacterEncoding("utf-8");  
  31.         PrintWriter out = response.getWriter();  
  32.         String msg = null;  
  33.         if(username!=null&&password!=null)  
  34.         {  
  35.             msg = "success";  
  36.               
  37.             try  
  38.             {  
  39.                 String uri = "jdbc:mysql://127.0.0.1/monitordb";  
  40.                 String insertSql = "insert into user values(?,?)";  
  41.                 conn = DriverManager.getConnection(uri, "root""loulijun");  
  42.                 sql = conn.prepareStatement(insertSql);  
  43.                 sql.setString(1,username);  
  44.                 sql.setString(2,password);  
  45.                 int status = sql.executeUpdate();  
  46.                 if(status!=0)  
  47.                 {  
  48.                     System.out.print("添加数据成功!");  
  49.                 }else  
  50.                 {  
  51.                     System.out.print("添加数据失败");  
  52.                 }  
  53.                 conn.close();  
  54.             }  
  55.             catch (SQLException e)  
  56.             {  
  57.                 System.out.print(e);  
  58.             }  
  59.         }else  
  60.         {  
  61.             msg = "failed";  
  62.         }  
  63.         out.print(msg);  
  64.         out.flush();  
  65.         out.close();  
  66.     }  
  67.   
  68.     public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException  
  69.     {  
  70.         doGet(request, response);  
  71.     }  
  72.   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值