zoukankan      html  css  js  c++  java
  • Android美工坊一个QQ登录验证的小例子

    客户端:

    1、登录时检查网络状态

    2、登录加载进度条

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

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

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

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

    服务器端:

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

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

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

    下面是效果图:

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

    客户端代码:

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

    View Code
    package com.loulijun.logindemo;
    
    import java.security.MessageDigest;
    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 android.app.Activity;
    import android.app.AlertDialog;
    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.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class LoginDemoActivity extends Activity {
        /** Called when the activity is first created. */
        private Button loginBtn;
        private Button registerBtn;
        private EditText inputUsername;
        private EditText inputPassword;
        private CheckBox saveInfoItem;
        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;
        
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            loginBtn = (Button)findViewById(R.id.login_btn_login);
            registerBtn = (Button)findViewById(R.id.login_btn_zhuce);
            inputUsername = (EditText)findViewById(R.id.login_edit_account);
            inputPassword = (EditText)findViewById(R.id.login_edit_pwd);
            saveInfoItem = (CheckBox)findViewById(R.id.login_cb_savepwd);
            
            sp = getSharedPreferences("userdata",0);
            //初始化数据
            LoadUserdata();
    
            //检查网络
            CheckNetworkState();
    
            //监听记住密码选项
            saveInfoItem.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener()  
            {  
                @Override  
                public void onCheckedChanged(CompoundButton buttonView,  
                        boolean isChecked) {  
                    // TODO Auto-generated method stub  
                    //载入用户信息
                   
                    Editor editor = sp.edit();
                    
                    if(saveInfoItem.isChecked())
                    {
                         //获取已经存在的用户名和密码
                        String realUsername = sp.getString("username", "");
                        String realPassword = sp.getString("password", "");
                        editor.putBoolean("checkstatus", true);
                        editor.commit();
                         
                         if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))
                         {
                            //清空输入框
                            inputUsername.setText("");
                              inputPassword.setText("");
                              //设置已有值
                             inputUsername.setText(realUsername);
                             inputPassword.setText(realPassword);
                         }
                    }else
                    {
                        editor.putBoolean("checkstatus", false);
                        editor.commit();
                        //清空输入框
                        inputUsername.setText("");
                         inputPassword.setText("");
                    }
                   
                }  
                  
            });  
            //登录
            loginBtn.setOnClickListener(new Button.OnClickListener()
            {
    
                @Override
                public void onClick(View arg0) {
                    mDialog = new ProgressDialog(LoginDemoActivity.this);
                    mDialog.setTitle("登陆");
                    mDialog.setMessage("正在登陆服务器,请稍后...");
                    mDialog.show();
                    Thread loginThread = new Thread(new LoginThread());
                    
                    loginThread.start();
    
                }
                
            });
            
            registerBtn.setOnClickListener(new Button.OnClickListener()
            {
    
                @Override
                public void onClick(View arg0) {
                    Intent intent = new Intent();
                    intent.setClass(LoginDemoActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }
                
            });
        }
        
        
        private boolean loginServer(String username, String password)
        {
            boolean loginValidate = false;
            //使用apache HTTP客户端实现
            String urlStr = "http://192.168.1.101:8080/LoginServlet/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;
        }
    
        
        //判断是否记住密码,默认记住
        private boolean isRemembered() {
            try {
                if (saveInfoItem.isChecked()) {
                    return true;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
        //初始化用户数据
        private void LoadUserdata()
        {
            boolean checkstatus = sp.getBoolean("checkstatus", false);
            if(checkstatus)
            {
                saveInfoItem.setChecked(true);
                //载入用户信息
                 //获取已经存在的用户名和密码
                String realUsername = sp.getString("username", "");
                String realPassword = sp.getString("password", "");
                if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))
                {
                    inputUsername.setText("");
                    inputPassword.setText("");
                    inputUsername.setText(realUsername);
                    inputPassword.setText(realPassword);
                }    
            }else
            {
                saveInfoItem.setChecked(false);
                inputUsername.setText("");
                inputPassword.setText("");
            }
            
        }
        //检查网络状态
        public void CheckNetworkState()
        {
            boolean flag = false;
            ConnectivityManager manager = (ConnectivityManager)getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
            State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            //如果3G、wifi、2G等网络状态是连接的,则退出,否则显示提示信息进入网络设置界面
            if(mobile == State.CONNECTED||mobile==State.CONNECTING)
            return;
            if(wifi == State.CONNECTED||wifi==State.CONNECTING)
            return;
            showTips();
        }
        
        private void showTips()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setTitle("没有可用网络");
            builder.setMessage("当前网络不可用,是否设置网络?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 如果没有网络连接,则进入网络设置界面
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    LoginDemoActivity.this.finish();
                }
            });
            builder.create();
            builder.show();
        }
        //Handler
        Handler handler = new Handler()
        {
            public void handleMessage(Message msg)
            {
                switch(msg.what)
                {
                case 0:
                    mDialog.cancel();
    
                    Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(LoginDemoActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 1:
                    mDialog.cancel();
                    Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    mDialog.cancel();
                    Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();
                    break;
                
                }
                
            }
        };
        
        //LoginThread线程类
        class LoginThread implements Runnable
        {
    
            @Override
            public void run() {
                String username = inputUsername.getText().toString();
                String password = inputPassword.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 = inputUsername.getText().toString();
                            password = inputPassword.getText().toString();
                        }
                    }
                }else
                {
                    password = md5(password);
                }
                System.out.println("username="+username+":password="+password);
                    
                //URL合法,但是这一步并不验证密码是否正确
                boolean loginValidate = loginServer(username, password);
                System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg);
                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);
                }
            }
            
        }
        
        
        /**
         * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全  
         * @param str
         * @return
         */
        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();  
        }  
       
        
    }

    注册代码

    View Code
    package com.loulijun.logindemo;
    
    import java.security.MessageDigest;
    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.loulijun.logindemo.LoginDemoActivity.LoginThread;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class RegisterActivity extends Activity {
        private EditText newUser,newPassword,confirmPassword;
        private Button registerBtn, clearBtn;
        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;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.register);
            newUser = (EditText)findViewById(R.id.newUser_input);
            newPassword = (EditText)findViewById(R.id.newPassword_input);
            confirmPassword = (EditText)findViewById(R.id.Confirm_input);
            registerBtn = (Button)findViewById(R.id.registerbtn);
            clearBtn = (Button)findViewById(R.id.clearbtn);
            registerBtn.setOnClickListener(new Button.OnClickListener()
            {
    
                @Override
                public void onClick(View v) {
                    String newusername = newUser.getText().toString();
                    String newpassword = md5(newPassword.getText().toString());
                    String confirmpwd = md5(confirmPassword.getText().toString());
                    
                    if(newpassword.equals(confirmpwd))
                    {
                        SharedPreferences sp = getSharedPreferences("userdata",0);
                        Editor editor = sp.edit();
                        editor.putString("username", newusername);
                        editor.putString("password", newpassword);
                        editor.commit();
                        mDialog = new ProgressDialog(RegisterActivity.this);
                        mDialog.setTitle("登陆");
                        mDialog.setMessage("正在登陆服务器,请稍后...");
                        mDialog.show();
                        Thread loginThread = new Thread(new RegisterThread());
                        loginThread.start();
                        
                    }else
                    {
                        Toast.makeText(getApplicationContext(), "您两次输入的密码不一致!", Toast.LENGTH_SHORT).show();
                    }
                }
                
            });
            
            clearBtn.setOnClickListener(new Button.OnClickListener()
            {
    
                @Override
                public void onClick(View v) {
                    newUser.setText("");
                    newPassword.setText("");
                    confirmPassword.setText("");
                }
                
            });
        }
        
        //初始化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://192.168.1.101:8080/LoginServlet/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;
            }
         
        //Handler
            Handler handler = new Handler()
            {
                public void handleMessage(Message msg)
                {
                    switch(msg.what)
                    {
                    case 0:
                        mDialog.cancel();
                        showDialog("注册成功!");
                        break;
                    case 1:
                        mDialog.cancel();
                        Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        mDialog.cancel();
                        Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();
                        break;
                    
                    }
                    
                }
            };
            
            
            //RegisterThread线程类
            class RegisterThread implements Runnable
            {
    
                @Override
                public void run() {
                    String username = newUser.getText().toString();
                    String password = md5(newPassword.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);
                    }
                }
                
            }
        
        private void showDialog(String str)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("注册");
            builder.setMessage(str);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.setClass(RegisterActivity.this, LoginDemoActivity.class);
                    startActivity(intent);
                    finish();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
        
        /**
         * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全  
         * @param str
         * @return
         */
        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();  
        }  
          
    }

    主界面的布局:

    View Code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/loginRoot"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <LinearLayout 
            android:id="@+id/linear1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/default_bg"
            android:orientation="vertical"
            >
            <RelativeLayout 
                android:id="@+id/relativelayout2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15.0px"
                android:layout_marginRight="15.0px"
                android:layout_marginTop="62.0px"
                android:background="@drawable/login_back"
                android:paddingBottom="10.0px"
                android:paddingTop="21.0px"
                >
                <ImageView
                    android:id="@+id/faceImg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/login_head"
                    />
                <EditText
                    android:id="@+id/login_edit_account"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginBottom="5.0dip"
                    android:layout_marginLeft="5.0dip"
                    android:layout_marginTop="5.0dip"
                    android:layout_marginRight="5.0dip"
                    android:layout_toRightOf="@+id/faceImg"
                    android:background="@drawable/edit_login"
                    android:hint="@string/username_hint"
                    android:singleLine="true"
                    android:paddingLeft="45.0sp"
                    android:saveEnabled="true"
                    android:textColor="#ff3f3f3f"
                    />
                <TextView 
                    android:id="@+id/textview01"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/login_edit_account"
                    android:layout_alignLeft="@+id/login_edit_account"
                    android:layout_alignTop="@+id/login_edit_account"
                    android:layout_marginRight="15.0sp"
                    android:gravity="center_vertical"
                    android:paddingLeft="7.0sp"
                    android:text="@string/username_input"
                    android:textColor="#ff3f3f3f"
                    android:textSize="16.0dip"
                    />
                <ImageButton 
                    android:id="@+id/usernamespinner"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/login_edit_account"
                    android:layout_alignRight="@+id/login_edit_account"
                    android:layout_alignTop="@+id/login_edit_account"
                    android:layout_marginRight="1.0dip"
                    android:background="@drawable/more_select"
                    />
                
                <EditText
                    android:id="@+id/login_edit_pwd"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignLeft="@+id/login_edit_account"
                    android:layout_alignRight="@+id/login_edit_account"
                    android:layout_below="@+id/login_edit_account"
                    android:layout_marginRight="1.0dip"
                    android:background="@drawable/edit_login"
                    android:password="true"
                    android:singleLine="true"
                    android:paddingLeft="45.0sp"
                    android:saveEnabled="true"
                    android:hint="@string/password_hint"
                    />
                <TextView 
                    android:id="@+id/textview02"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/login_edit_pwd"
                    android:layout_alignRight="@+id/textview01"
                    android:layout_alignTop="@+id/login_edit_pwd"
                    android:gravity="center_vertical"
                    android:paddingLeft="7.0sp"
                    android:text="@string/password_input"
                    android:textColor="#ff3f3f3f"
                    android:textSize="16.0dip"                
                    />
                <CheckBox 
                    android:id="@+id/login_cb_savepwd"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/login_btn_login"
                    android:button="@drawable/btn_check"
                    android:paddingLeft="39.0px"
                    android:text="@string/opt_remember"
                    android:textColor="#ff222222"
                    android:textSize="16.0sp"
                    />
                <Button
                    android:id="@+id/login_btn_login"
                    android:layout_width="90.0dp"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/textview02"
                    android:layout_toLeftOf="@+id/login_btn_zhuce"
                    android:layout_marginTop="7.0px"
                    android:text="@string/login" />
                <Button
                    android:id="@+id/login_btn_zhuce"
                    android:layout_width="90.0dp"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_below="@+id/textview02"
                    android:layout_marginTop="7.0px"
                    android:text="@string/zhuce" />
            </RelativeLayout>
        </LinearLayout>
    
    </LinearLayout>

    服务器端:

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

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

    web.xml

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5"> 
    
    
      <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.loulijun.login.LoginServlet</servlet-class>
      </servlet>
     
      <!-- Define the Manager Servlet Mapping -->
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
    
        <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>com.loulijun.login.RegisterServlet</servlet-class>
      </servlet>
     
      <!-- Define the Manager Servlet Mapping -->
      <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/RegisterServlet</url-pattern>
      </servlet-mapping>
     
    </web-app>

    LoginServlet.java:用于登录信息的Servlet

    View Code
    package com.loulijun.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;
    
    public class LoginServlet extends HttpServlet
    {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
        {
            
            Connection conn;
            PreparedStatement sql;
            ResultSet rs;
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
            }
            catch (Exception e)
            {
                System.out.print(e);
            }
    
            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;
            String uri = "jdbc:mysql://127.0.0.1/monitordb";
            String selectsql = "select username,password from user where username=? and password=?";
            
            try
            {
                conn = DriverManager.getConnection(uri, "root", "loulijun");
                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 (SQLException 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);
        }
    
    }

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

    View Code
    package com.loulijun.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;
    
    public class RegisterServlet extends HttpServlet
    {
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
        {
            Connection conn;
            PreparedStatement sql;
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
            }
            catch (Exception e)
            {
                System.out.print(e);
            }
    
            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
                {
                    String uri = "jdbc:mysql://127.0.0.1/monitordb";
                    String insertSql = "insert into user values(?,?)";
                    conn = DriverManager.getConnection(uri, "root", "loulijun");
                    sql = conn.prepareStatement(insertSql);
                    sql.setString(1,username);
                    sql.setString(2,password);
                    int status = sql.executeUpdate();
                    if(status!=0)
                    {
                        System.out.print("添加数据成功!");
                    }else
                    {
                        System.out.print("添加数据失败");
                    }
                    conn.close();
                }
                catch (SQLException 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);
        }
    
    }
  • 相关阅读:
    查看Oracle连接数 限制某个用户的连接数
    (原创网上办法经过改良)系统重装后,如何快速的回复oracle 10g(测试环境:windows server 2003 sp1+Oracle 10g)
    Response.Redirect报"正在中止进程"异常的处理
    快速使网页变灰色
    .NET创建Windows服务[转]
    [收集]javascript中得到当前窗口的高和宽
    [转帖]javascript版 UrlEncode和UrlDecode函数
    js异步读取xml(支持ff和xpath)
    辞职考研后记
    BCB6 E2494 Unrecognized __declspec modifier
  • 原文地址:https://www.cnblogs.com/loulijun/p/2442583.html
Copyright © 2011-2022 走看看