一张图看懂Android注册登录+服务端

整个环境是运行在Android虚拟机+tomcat服务器+MySQL上面的。。。需要对服务端以及Android都要比较熟悉。才能够比较完整的配置下来。。。
这里写图片描述

Android端相关代码:
1.注册登录成功后的页面的类

package com.test.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class UserInfoActivity extends Activity {
    private TextView tvUsername;
    private TextView tvGender;
    private TextView tvAge;
    private TextView tvPhone;
    private TextView tvEmail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info_activity);
        initViews();
        Intent intent = getIntent();
        displayUserInfo(intent);
    }
    private void initViews() {
        tvUsername = (TextView) findViewById(R.id.usr_info_username);
        tvGender   = (TextView) findViewById(R.id.usr_info_gender);
        tvAge      = (TextView) findViewById(R.id.usr_info_age);
        tvPhone    = (TextView) findViewById(R.id.usr_info_phone);
        tvEmail    = (TextView) findViewById(R.id.usr_info_email);
    }

    private void displayUserInfo(Intent intent) {
        String username = intent.getStringExtra("username");
        String gender   = intent.getStringExtra("gender");
        int age         = intent.getIntExtra("age", -1);
        String phone    = intent.getStringExtra("phone");
        String email    = intent.getStringExtra("email");       
        tvUsername.setText(username);
        tvGender.setText(gender);
        tvAge.setText(String.valueOf(age));
        tvPhone.setText(phone);
        tvEmail.setText(email);
    }
}

2.注册用户的类

package com.test.login;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.MailTo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class CreateUserActivity extends Activity implements OnClickListener {

    public static final String CREATE_ACCOUNT_URL = "http://10.0.2.2:8080/test/servlet/NewAccount";
    public static final int MSG_CREATE_RESULT = 1;

    private EditText eUsername;
    private EditText ePwd1;
    private EditText ePwd2;
    private RadioGroup rGender;
    private EditText eAge;
    private EditText ePhone;
    private EditText eEmail;

    private Button btnSubmit;
    private Button btnReset;

    ProgressDialog progress;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case MSG_CREATE_RESULT:
                progress.dismiss();
                JSONObject json = (JSONObject) msg.obj;
                hanleCreateAccountResult(json);
                break;
            }
        }   
    };

    private void hanleCreateAccountResult(JSONObject json) {
        /*
         *   result_code: 
         * 0  注册成功
         * 1  用户名已存在
         * 2 数据库操作异常
         * */
        int result;
        try {
            result = json.getInt("result_code");
        } catch (JSONException e) {
            Toast.makeText(this, "没有获取到网络的响应!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            return;
        }

        if(result == 1) {
            Toast.makeText(this, "用户名已存在!", Toast.LENGTH_LONG).show();
            return;
        }

        if(result == 2) {
            Toast.makeText(this, "注册失败!服务端出现异常!", Toast.LENGTH_LONG).show();
            return;
        }

        if(result == 0) {
            Toast.makeText(this, "注册成功!前往登陆界面!", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_user_activity);

        initViews();
    }

    private void initViews() {
        eUsername = (EditText)findViewById(R.id.new_username);
        ePwd1 = (EditText)findViewById(R.id.new_password_1);
        ePwd2 = (EditText)findViewById(R.id.new_password_2);
        rGender = (RadioGroup)findViewById(R.id.new_radio_group_gender);
        eAge = (EditText)findViewById(R.id.new_age);
        ePhone = (EditText)findViewById(R.id.new_phone);
        eEmail = (EditText)findViewById(R.id.new_email);
        btnSubmit = (Button)findViewById(R.id.new_btn_submit);
        btnReset = (Button)findViewById(R.id.new_btn_reset);
        btnSubmit.setOnClickListener(this);
        btnReset.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.new_btn_submit:
            handleCreateAccount();
            break;
        case R.id.new_btn_reset:
            handleReset();
            break;
        }

    }

    private void handleCreateAccount() {
        boolean isUsernameValid = checkUsername();
        if(!isUsernameValid) {
            Toast.makeText(this, "用户名不正确,请重新输入", Toast.LENGTH_LONG).show();
            return;
        }

        int pwdResult = checkPassword();
        if(pwdResult == 1) {
            Toast.makeText(this, "两次输入的密码不一致,请确认!", Toast.LENGTH_LONG).show();
            return;
        } 
        if (pwdResult == 2) {
            Toast.makeText(this, "密码不能为空!", Toast.LENGTH_LONG).show();
            return;
        }

        int isAgeValid = checkAge();
        if(isAgeValid == -1) {
            Toast.makeText(this, "年龄不能为空!", Toast.LENGTH_LONG).show();
            return;
        }
        if(isAgeValid == -2) {
            Toast.makeText(this, "年龄超出范围(1~100)!", Toast.LENGTH_LONG).show();
            return;
        }
        if(isAgeValid == -3) {
            Toast.makeText(this, "年龄格式输入错误,请不要输入字母、符号等其他字符串!", Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(ePhone.getText().toString())) {
            Toast.makeText(this, "请输入电话号码!", Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(eEmail.getText().toString())) {
            Toast.makeText(this, "请输入邮箱!", Toast.LENGTH_LONG).show();
            return;
        }

        createAccount();
    }

    private void createAccount() {
        progress = new ProgressDialog(this);
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
        progress.show(this, null, "注册中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("yanghongbing", "Start Network!");
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(CREATE_ACCOUNT_URL);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", eUsername.getText().toString()));
                params.add(new BasicNameValuePair("password", ePwd1.getText().toString()));
                RadioButton selectedGender = (RadioButton)CreateUserActivity.this.findViewById(rGender.getCheckedRadioButtonId());
                params.add(new BasicNameValuePair("gender", 
                        selectedGender.getText().toString()));
                params.add(new BasicNameValuePair("age", eAge.getText().toString()));
                params.add(new BasicNameValuePair("phone", ePhone.getText().toString()));
                params.add(new BasicNameValuePair("email", eEmail.getText().toString()));
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if(httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d("yanghongbing", "Network OK!");
                        HttpEntity entity = httpResponse.getEntity();
                        String entityStr = EntityUtils.toString(entity);
                        String jsonStr = entityStr.substring(entityStr.indexOf("{"));
                        JSONObject json = new JSONObject(jsonStr);
                        sendMessage(MSG_CREATE_RESULT, json);

                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start(); 
    }

    private boolean checkUsername() {
        String username = eUsername.getText().toString();
        if(TextUtils.isEmpty(username)) {
            return false;
        }
        return true;
    }

    private int checkPassword() {
        /*
         * return value:
         * 0 password valid
         * 1 password not equal 2 inputs
         * 2 password empty
         * */
        String pwd1 = ePwd1.getText().toString();
        String pwd2 = ePwd2.getText().toString();
        if(!pwd1.equals(pwd2)) {
            return 1;
        } else if(TextUtils.isEmpty(pwd1)) {
            return 2;
        } else {
            return 0;
        }
    }

    private int checkAge() {
        /*
         * return value
         * 0 输入合法
         * -1 输入为空
         * -2输入为负数
         * -3输入为非数值字符串或包括小数
         * */
        int ageNum;
        String age = eAge.getText().toString();
        if(TextUtils.isEmpty(age)) {
            return -1;
        }
        try {
            ageNum = Integer.parseInt(age);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return -3;
        }
        if(ageNum <= 0 || ageNum > 100) {
            return -2;
        }
        return 0;
    }
    private void handleReset() {
        eUsername.setText("");
        ePwd1.setText("");
        ePwd2.setText("");
        ((RadioButton)(rGender.getChildAt(0))).setChecked(true);
        eAge.setText("");
        ePhone.setText("");
        eEmail.setText("");
    }   
    private void sendMessage(int what, Object obj) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}

3.登录页面的类

package com.test.login;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
    private EditText loginUsername;
    private EditText loginPassword;
    private Button loginButton;
    private Button createButton;

    private ProgressDialog loginProgress;

    public static final int MSG_LOGIN_RESULT = 0;

    public String serverUrl = "http://10.0.2.2:8080/test/servlet/loadMessage";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {   
            case MSG_LOGIN_RESULT:
                loginProgress.dismiss();
                JSONObject json = (JSONObject) msg.obj;
                handleLoginResult(json);
                break;
            }
        };
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        initViews();
    }
    private void initViews() {
        loginUsername = (EditText)findViewById(R.id.login_username);
        loginPassword = (EditText)findViewById(R.id.login_password);
        loginButton   = (Button)findViewById(R.id.login);
        createButton  = (Button)findViewById(R.id.create_count);

        loginButton.setOnClickListener(this);
        createButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.login:
            handleLogin();
            break;
        case R.id.create_count:
            handleCreateCount();
            break;
        default:
            break;  
        }

    }
    private void handleLogin() {
        String username = loginUsername.getText().toString();
        String password = loginPassword.getText().toString();
        login(username, password);
    }
    private void login(final String username, final String password) {
        loginProgress = new ProgressDialog(this);
        loginProgress.setCancelable(false);
        loginProgress.setCanceledOnTouchOutside(false);
        loginProgress.show(this, null, "登陆中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("yanghongbing", "start network!");
                HttpClient client = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(serverUrl);
                List<NameValuePair> params = new ArrayList<NameValuePair>(); 
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                HttpResponse httpResponse = null;
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    httpResponse = client.execute(httpPost);
                    if(httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d("yanghongbing", "network OK!");
                        HttpEntity entity = httpResponse.getEntity();
                        String entityString = EntityUtils.toString(entity);
                        String jsonString = entityString.substring(entityString.indexOf("{"));
                        Log.d("yanghongbing", "entity = " + jsonString);
                        JSONObject json = new JSONObject(jsonString);
                        sendMessage(MSG_LOGIN_RESULT, json);
                        Log.d("yanghongbing", "json = " + json);
                    }
                } catch (UnsupportedEncodingException e) {
                    Log.d("yanghongbing", "UnsupportedEncodingException");
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    Log.d("yanghongbing", "ClientProtocolException");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.d("yanghongbing", "IOException");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    Log.d("yanghongbing", "IOException");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void handleCreateCount() {
        Intent intent = new Intent(this, CreateUserActivity.class);
        startActivity(intent);
        finish();
    }

    private void handleLoginResult(JSONObject json){
        /*
         * login_result:
         * -1:登陆失败,未知错误!
         * 0: 登陆成功!
         * 1:登陆失败,用户名或密码错误!
         * 2:登陆失败,用户名不存在!
         * */
        int resultCode = -1;
        try {
            resultCode = json.getInt("result_code");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch(resultCode) {
        case 0:
            onLoginSuccess(json);
            break;
        case 1:
            Toast.makeText(this, "用户名或密码错误!", Toast.LENGTH_LONG).show();
            break;
        case 2:
            Toast.makeText(this, "用户名不存在!", Toast.LENGTH_LONG).show();
            break;
        case -1:
        default:
            Toast.makeText(this, "登陆失败!未知错误!", Toast.LENGTH_LONG).show();
            break;
        }
    }

    private void onLoginSuccess(JSONObject json) {
        Intent intent = new Intent(this, UserInfoActivity.class);

        try {
            intent.putExtra("username", json.getString("username"));
            intent.putExtra("gender", json.getString("gender"));
            intent.putExtra("age", json.getInt("age"));
            intent.putExtra("phone", json.getString("phone"));
            intent.putExtra("email", json.getString("email"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        startActivity(intent);
        finish();
    }
    private void sendMessage(int what, Object obj) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}

Android的xml:
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:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="80dip">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/login_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_weight="1" >

            <requestFocus />
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密    码"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/login_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dip"
            android:inputType="textPassword" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip" 
        android:gravity="center">

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登陆" />

        <Button
            android:id="@+id/create_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册" />

    </LinearLayout>

</LinearLayout>

2.注册信息的xml
这里写图片描述

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/UserInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_weight="0.85"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用户名"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="5dip" >

                <requestFocus />
            </EditText>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密    码"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_password_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="5dip"
                android:inputType="textPassword" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密    码"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_password_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="5dip"
                android:inputType="textPassword" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_marginTop="15dip">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="性    别"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <RadioGroup
                android:id="@+id/new_radio_group_gender"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
                android:layout_marginLeft="5dip" 
                android:orientation="horizontal"
                >

                <RadioButton
                    android:id="@+id/new_gender_boy"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:layout_marginLeft="10dip" 
                    android:text="男" />


            <RadioButton
                android:id="@+id/new_gender_girl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dip" 
                android:text="女" />
            </RadioGroup>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_marginTop="15dip">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年    龄"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dip" 
                android:layout_weight="1"
                android:inputType="number" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip" >

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="电    话"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="5dip" 
                android:inputType="phone" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip" >

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Email "
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <EditText
                android:id="@+id/new_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginLeft="5dip" 
                android:inputType="textEmailAddress" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:layout_marginTop="30dip"
            android:gravity="center">

            <Button
                android:id="@+id/new_btn_submit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="提交" />

            <Button
                android:id="@+id/new_btn_reset"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="重置" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

3.登录后显示信息的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:layout_marginLeft="20dip"
    android:layout_marginRight="20dip">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="50dip">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/usr_info_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip" >

        <LinearLayout
            android:id="@+id/linearLayout3"
            android:layout_width="fill_parent"
            android:layout_height="match_parent" 
            android:layout_weight="1">

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="性别"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/usr_info_gender"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceLarge" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" >

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年龄"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/usr_info_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceLarge" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip" >

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电话"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/usr_info_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="10dip">

        <TextView
            android:id="@+id/textView9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="邮箱"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/usr_info_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>

</LinearLayout>

服务端:
服务端对我这个做Android的来说还是有一些繁琐,大部分的调试时间都花在这里了,也算是复习的javaweb的一些操作了。
用的是web版本的eclipse:
tomcat是6.0的版本,配置到了eclipse里面,直接在eclipse上面运行的服务器,
注意myeclipseweb工程导入到eclipse里面要做的改动,网上有相关教程。
添加一个项目到服务器里的操作,
MySQL的操作
1.数据库管理类

package com.test.database;

import java.awt.List;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.lang.Object;
import com.mysql.jdbc.Connection;

public class DBManager {

    public final static String TABLE_NAME = "login_info";

    public final static String COLUMN_USERNAME = "username";
    public final static String COLUMN_PASSWORD = "password";
    public final static String COLUMN_GENDER = "gender";
    public final static String COLUMN_AGE = "age";
    public final static String COLUMN_PHONE = "phone";
    public final static String COLUMN_EMAIL = "email";

    public Statement getStatement() {
        Connection connection = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&characterEncoding=utf8", "root", "root");
            stmt = connection.createStatement();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return stmt;
    }

    public ArrayList<HashMap<String, Object>> getDatabaseContents() {
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = null;
        String sql = "select * from " + TABLE_NAME;
        Statement stmt = getStatement();
        ResultSet rst = null;
        try {
            rst = stmt.executeQuery(sql);
            if(rst != null) {
                while(rst.next()) {
                    map = new HashMap<String, Object>();
                    map.put(COLUMN_USERNAME, rst.getString(COLUMN_USERNAME));
                    map.put(COLUMN_PASSWORD, rst.getString(COLUMN_PASSWORD));
                    map.put(COLUMN_GENDER, rst.getString(COLUMN_GENDER));
                    map.put(COLUMN_AGE, rst.getInt(COLUMN_AGE));
                    map.put(COLUMN_PHONE, rst.getString(COLUMN_PHONE));
                    map.put(COLUMN_EMAIL, rst.getString(COLUMN_EMAIL));
                    list.add(map);
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }

    public ResultSet query(String sql) {
        ResultSet rst = null;
        Statement stmt = getStatement();
        System.out.println("stmt = " + stmt);
        try {
            rst = stmt.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rst;
    }

    public int update(String sql) {
        Statement stmt = getStatement();
        int result = 0;
        try {
            result = stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}

2.登录的处理类

package com.test.servlet;

import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.test.database.DBManager;

public class loadMessage extends HttpServlet {
    private final static long serialVersionUID = 1L;
    public loadMessage() {
        super();
    }
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    //  request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8" );
        DataOutputStream dos = new DataOutputStream(response.getOutputStream());
        /*
         String message="mysql数据库中的内容:";
         DBManager db=new DBManager();
         ArrayList<HashMap<String,Object>> list = db.getDatabaseContents();
         HashMap<String,Object> map = null;
           for(int i=0;i<list.size();i++){
               map = list.get(i);
               String username = (String) map.get(DBManager.COLUMN_USERNAME);
               String password = (String) map.get(DBManager.COLUMN_PASSWORD);
               String gender = (String) map.get(DBManager.COLUMN_GENDER);
               int age = (int) map.get(DBManager.COLUMN_AGE);
               String phone = (String) map.get(DBManager.COLUMN_PHONE);
               String email = (String) map.get(DBManager.COLUMN_EMAIL);
               String userInfo = "{" + username + "\n"
                       + password + "\n"
                       + gender + "    " + age + "\n"
                       + phone + "\n"
                       + email + "\n"
                       + "}";
               message += userInfo;
           }
         message=message+"Access数据库中的内容:\r\n";
        System.out.println("message = " + message);
        dos.writeUTF(message);
        dos.flush();
        dos.close();
        */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String result = doLogin(username, password);
        System.out.println("result = " + result);
        dos.writeUTF(result);
    }
    private String doLogin(String username,
            String password) {
        /*
         * login_result:
         * -1:登陆失败,未知错误!
         * 0: 登陆成功!
         * 1:登陆失败,用户名或密码错误!
         * 2:登陆失败,用户名不存在!
         * */
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        String sql = "select * from " + DBManager.TABLE_NAME + " where " + DBManager.COLUMN_USERNAME + " = " + "'" + username + "'" ;
        System.out.println("url = " + sql);
        DBManager db = new DBManager();
        ResultSet rst = db.query(sql);
        try {
            rst.next();
            String pwd = rst.getString(DBManager.COLUMN_PASSWORD);
            if(!password.equals(pwd)) {
                resultMap.put("result_code", 1);
            } else {
                resultMap.put("result_code", 0);
                resultMap.put(DBManager.COLUMN_USERNAME, rst.getString(DBManager.COLUMN_USERNAME));
                resultMap.put(DBManager.COLUMN_GENDER, rst.getString(DBManager.COLUMN_GENDER));
                resultMap.put(DBManager.COLUMN_AGE, rst.getInt(DBManager.COLUMN_AGE));
                resultMap.put(DBManager.COLUMN_PHONE, rst.getString(DBManager.COLUMN_PHONE));
                resultMap.put(DBManager.COLUMN_EMAIL, rst.getString(DBManager.COLUMN_EMAIL));
            }
        } catch (SQLException e) {
            resultMap.put("result_code", 2);
            e.printStackTrace();
        }
        return (new Gson()).toJson(resultMap);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
    public void init() throws ServletException {
        // Put your code here
    }

}

3.注册的处理类

package com.test.servlet;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.gson.Gson;
import com.test.database.DBManager;

public class NewAccount extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8" );
        //request.setCharacterEncoding("UTF-8");
        DataOutputStream dos = new DataOutputStream(response.getOutputStream());

        HashMap<String, Object> params = getParamsFromRequest(request);
        String result = handleNewUser(params);
        dos.writeUTF(result);
    }

    private String handleNewUser(HashMap<String, Object> params) {
        /*
         *   result_code: 
         * 0 用户名不存在,可以正常注册
         * 1  用户名已存在
         * 2 数据库操作异常
         * */
        HashMap<String, Object> result = new HashMap<String, Object>();
        String username = (String) params.get(DBManager.COLUMN_USERNAME);
        if(isUsernameExsited(username)) {
            result.put("result_code", 1);
        } else {
            DBManager db = new DBManager();
            String password = (String) params.get(DBManager.COLUMN_PASSWORD);
            String gender = (String) params.get(DBManager.COLUMN_GENDER);
            try {
                gender = new String(gender.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String age = (String) params.get(DBManager.COLUMN_AGE);
            String phone = (String) params.get(DBManager.COLUMN_PHONE);
            String email = (String) params.get(DBManager.COLUMN_EMAIL);
            String sql = "Insert into " + DBManager.TABLE_NAME + " values (" 
                    + "'" + username + "',"
                    + "'" + password + "',"
                    + "'" + gender + "',"
                    +  age + ","
                    + "'" + phone + "',"
                    + "'" + email + "')";
            System.out.println("sql = " + sql);
            int executeResult = db.update(sql);
            if(executeResult == 0) {
                result.put("result_code", 2);
            } else {
                result.put("result_code", 0);
            }
        }
        return (new Gson()).toJson(result);
    }

    HashMap<String, Object> getParamsFromRequest(HttpServletRequest request) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put(DBManager.COLUMN_USERNAME, request.getParameter(DBManager.COLUMN_USERNAME));
        params.put(DBManager.COLUMN_PASSWORD, request.getParameter(DBManager.COLUMN_PASSWORD));
        params.put(DBManager.COLUMN_GENDER, request.getParameter(DBManager.COLUMN_GENDER));
        params.put(DBManager.COLUMN_AGE, request.getParameter(DBManager.COLUMN_AGE));
        params.put(DBManager.COLUMN_PHONE, request.getParameter(DBManager.COLUMN_PHONE));
        params.put(DBManager.COLUMN_EMAIL, request.getParameter(DBManager.COLUMN_EMAIL));
        return params;
    }

    private boolean isUsernameExsited(String name) {
        boolean isExisted = true;
        DBManager db = new DBManager();
        String sql = "select * from " + DBManager.TABLE_NAME + " where " + DBManager.COLUMN_USERNAME + " = " + "'" + name + "'" ;
        ResultSet rst = db.query(sql);
        try {
            rst.next();
            String username = rst.getString(DBManager.COLUMN_USERNAME);
            isExisted = true;
        } catch (SQLException e) {
            isExisted = false;
            e.printStackTrace();
        }
        return isExisted;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

尤其注意web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>test</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>loadMessage</servlet-name>
    <servlet-class>com.test.servlet.loadMessage</servlet-class>
  </servlet>

  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>NewAccount</servlet-name>
    <servlet-class>com.test.servlet.NewAccount</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>loadMessage</servlet-name>
    <url-pattern>/servlet/loadMessage</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>NewAccount</servlet-name>
    <url-pattern>/servlet/NewAccount</url-pattern>
  </servlet-mapping>
</web-app>
  • 8
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值