android客户端登录&注册的实现

 

MainActivity多线程的实现:

package com.example.loginconnect;

import java.lang.ref.WeakReference;
import java.net.SocketTimeoutException;

import org.apache.http.conn.ConnectTimeoutException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.loginconnect.service.ServiceRulesException;
import com.example.loginconnect.service.UserService;
import com.example.loginconnect.service.UserServiceImpl;

public class MainActivity extends ActionBarActivity {
	private EditText username1;
	private EditText password1;

	private UserService userService = new UserServiceImpl();
	private static final int FLAG_LOGIN_SUCCESS = 1;
	private static final String MSG_LOGIN_ERROR = "登录出错。";
	private static final String MSG_LOGIN_SUCCESS = "登录成功。";
	public static final String MSG_LOGIN_FAILED = "用户名或密码错误。";
	public static final String MSG_SERVER_ERROR = "请求服务器错误。";
	public static final String MSG_SERVER_TIMEOUT = "请求服务器超时。";
	public static final String MSG_RESPONCE_TIMEOUT = "服务器响应超时。";
	private static ProgressDialog dialog;
	public static String loginName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button login = (Button) findViewById(R.id.login);
		Button resign = (Button) findViewById(R.id.resign);
		username1 = (EditText) findViewById(R.id.username);
		password1 = (EditText) findViewById(R.id.password);

		login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				loginName = username1.getText().toString();
				final String loginPassword = password1.getText().toString();

				// Toast.makeText(v.getContext(), "用户名:"+username,
				// Toast.LENGTH_LONG).show();
				// Toast.makeText(v.getContext(), "密码:"+password,
				// Toast.LENGTH_LONG).show();

				/**
				 * loading...
				 */

				if (dialog == null) {
					dialog = new ProgressDialog(MainActivity.this);
				}
				dialog.setTitle("请等待");
				dialog.setMessage("登录中...");
				dialog.setCancelable(false);
				dialog.show();

				/**
				 * 子线程
				 */
				Thread thread = new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							userService.userLogin(loginName, loginPassword);
							handler.sendEmptyMessage(FLAG_LOGIN_SUCCESS);

						} catch (ConnectTimeoutException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", MSG_SERVER_TIMEOUT);
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (SocketTimeoutException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg",
									MSG_RESPONCE_TIMEOUT);
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (ServiceRulesException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", e.getMessage());
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", MSG_LOGIN_ERROR);
							msg.setData(data);
							handler.sendMessage(msg);
						}
					}
				});
				thread.start();
			}
		});

		resign.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						ResignActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}

	private void showTip(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		if (str == MSG_LOGIN_SUCCESS) {
			Intent intent = new Intent(MainActivity.this, success.class);
			startActivity(intent);
			finish();
		}

	}

	private static class IHandler extends Handler {

		private final WeakReference<ActionBarActivity> mActivity;

		public IHandler(MainActivity activity) {
			mActivity = new WeakReference<ActionBarActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {

			if (dialog != null) {
				dialog.dismiss();
			}

			int flag = msg.what;
			switch (flag) {
			case 0:
				String errorMsg = (String) msg.getData().getSerializable(
						"ErrorMsg");
				((MainActivity) mActivity.get()).showTip(errorMsg);
				break;
			case FLAG_LOGIN_SUCCESS:
				((MainActivity) mActivity.get()).showTip(MSG_LOGIN_SUCCESS);
				break;

			default:
				break;
			}
		}
	}

	private IHandler handler = new IHandler(this);

	public String setUserName(String username) {
		username = loginName;
		return username;
	}

}

  

UserService 接口:
package com.example.loginconnect.service;

import org.json.JSONObject;

public interface UserService {

	public void userLogin(String loginName, String loginPassword)
			throws Exception;

	public void userResign(String loginName, String loginPassword,String surePassword,
			String realName, String cellphone1, String cellphone2,
			String cellphone3) throws Exception;
	public JSONObject selectUser(String loginName, String realname,
			String cellphone1, String cellphone2, String cellphone3)
			throws Exception;

}  

UserServiceImpl 继承自UserService ,实现与服务器交互:

package com.example.loginconnect.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.example.loginconnect.MainActivity;
import com.example.loginconnect.ResignActivity;
import com.example.loginconnect.success;
import com.google.gson.Gson;

public class UserServiceImpl implements UserService {
	private static final String TAG = "UserServiceImpl";

	// MainActivity person=new MainActivity();

	@Override
	public void userLogin(String loginName, String loginPassword)
			throws Exception {

		Log.d(TAG, loginName);
		Log.d(TAG, loginPassword);

		// Thread.sleep(3000);

		// 创建http对象
		HttpClient client = new DefaultHttpClient();

		/**
		 * post/json传值
		 */
		// String uri =
		// "http://10.138.108.131:8080/Test_MyService/login.action?username="
		// + loginName + "&password=" + loginPassword;
		// HttpGet get = new HttpGet(uri);
		// 响应
		// HttpResponse response = client.execute(get);
		String uri = "http://192.168.1.106:8080/MyService/login.action";
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpPost post = new HttpPost(uri);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("username", loginName);
			obj.put("password", loginPassword);
			// JSONObject json = new JSONObject();
			// Gson gson = new Gson();
			// String str = gson.toJson(obj);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			post.setParams(httpParams);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		HttpResponse response = client.execute(post);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			// String result = EntityUtils.toString(response.getEntity(),
			// "UTF-8");
			// System.out.println(result);

			String responseStr = EntityUtils.toString(response.getEntity());
			JSONObject json = new JSONObject(responseStr).getJSONObject("json");
			String result = json.getString("result");
			Log.d(TAG, result);
			if (result.equals("success")) {
				// return true;

			} else {
				// return false;
				throw new ServiceRulesException(MainActivity.MSG_LOGIN_FAILED);
			}

		} else {
			throw new ServiceRulesException(MainActivity.MSG_SERVER_ERROR);
		}

		// int statusCode = response.getStatusLine().getStatusCode();
		// if (statusCode != HttpStatus.SC_OK) {
		// throw new ServiceRulesException(MainActivity.MSG_SERVER_ERROR);
		// }
		// String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		//
		// if (result.equals("success")) {
		//
		// } else {
		// throw new ServiceRulesException(MainActivity.MSG_LOGIN_FAILED);
		// }

	}

	@Override
	public void userResign(String loginName, String loginPassword,
			String surePassword, String realName, String cellphone1,
			String cellphone2, String cellphone3) throws Exception {

		// if(loginPassword==surePassword){
		// }else{
		// throw new ServiceRulesException(ResignActivity.MSG_RESIGN_FAILED2);
		// }

		// Thread.sleep(3000);
		// 创建http对象
		/**
		 * GET 传值
		 */
		// String uri =
		// "http://10.138.106.30:8080/MyService/regist.action?username="
		// + loginName
		// + "&password="
		// + loginPassword
		// + "&realName="
		// + realName
		// + "&cellphone1="
		// + cellphone1
		// + "&cellphone2="
		// + cellphone2 + "&cellphone3=" + cellphone3;
		// http://10.138.108.131:8080/Test_MyService/login.action
		String uri = "http://192.168.1.106:8080/MyService/regist.action";
		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000); 
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpPost post = new HttpPost(uri);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("username", loginName);
			obj.put("password", loginPassword);
			obj.put("realname", realName);
			obj.put("cellphone1", cellphone1);
			obj.put("cellphone2", cellphone2);
			obj.put("cellphone3", cellphone3);
			// Gson gson = new Gson();
			// String str = gson.toJson(obj);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			post.setParams(httpParams);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		HttpResponse response = client.execute(post);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String responseStr = EntityUtils.toString(response.getEntity());
			JSONObject json = new JSONObject(responseStr).getJSONObject("json");
			String result = json.getString("result");

			if (result.equals("success")) {
			} else {
				throw new ServiceRulesException(
						ResignActivity.MSG_RESIGN_FAILED);
			}
		}

		// 响应
		// HttpResponse response = client.execute(get);

		// int statusCode = response.getStatusLine().getStatusCode();
		// if (statusCode != HttpStatus.SC_OK) {
		// throw new ServiceRulesException(ResignActivity.MSG_SERVER_ERROR);
		// }
		// String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		//
		// if (result.equals("success")) {
		//
		// } else {
		// throw new ServiceRulesException(ResignActivity.MSG_RESIGN_FAILED);
		// }

	}

	public JSONObject selectUser(String loginName, String realname,
			String cellphone1, String cellphone2, String cellphone3)
			throws Exception {
		String userName = "tom";
		// userName = person.setUserName(userName);
//		Thread.sleep(3000);
		// 创建http对象
		HttpClient client = new DefaultHttpClient();
		String uri = "http://192.168.1.106:8080/MyService/select.action";
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpPost post = new HttpPost(uri);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("username", userName);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			post.setParams(httpParams);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		HttpResponse response = client.execute(post);
		if (response.getStatusLine().getStatusCode() == 200) {
			String responseStr = EntityUtils.toString(response.getEntity());
			JSONObject json1 = new JSONObject(responseStr)
					.getJSONObject("json");
			JSONObject object = json1.getJSONObject("user");
			return object;
			

		} else {
			throw new ServiceRulesException(success.MSG_SERVER_ERROR);
		}
	}
}

  

ResignActivity 类实现注册的功能:
package com.example.loginconnect;

import java.lang.ref.WeakReference;
import java.net.SocketTimeoutException;

import org.apache.http.conn.ConnectTimeoutException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.loginconnect.service.ServiceRulesException;
import com.example.loginconnect.service.UserService;
import com.example.loginconnect.service.UserServiceImpl;

public class ResignActivity extends ActionBarActivity {

	private EditText account;
	private EditText password;
	private EditText sure_password;
	private EditText realname;
	private EditText phone1;
	private EditText phone2;
	private EditText phone3;
	private static ProgressDialog dialog;
	private UserService userService = new UserServiceImpl();

	private static final int FLAG_RESIGN_SUCCESS = 1;
	private static final String MSG_RESIGN_ERROR = "注册出错。";
	private static final String MSG_RESIGN_SUCCESS = "注册成功。";
	public static final String MSG_RESIGN_FAILED = "输入出现错误。";
	public static final String MSG_RESIGN_FAILED2 = "密码输入错误。";
	public static final String MSG_SERVER_ERROR = "请求服务器错误。";
	public static final String MSG_SERVER_TIMEOUT = "请求服务器超时。";
	public static final String MSG_RESPONCE_TIMEOUT = "服务器响应超时。";

	@Override
	protected void onCreate(Bundle savedInsanceState) {
		super.onCreate(savedInsanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.resign);

		account = (EditText) findViewById(R.id.account);
		password = (EditText) findViewById(R.id.password);
		sure_password = (EditText) findViewById(R.id.sure_password);
		realname = (EditText) findViewById(R.id.name);
		phone1 = (EditText) findViewById(R.id.phone1);
		phone2 = (EditText) findViewById(R.id.phone2);
		phone3 = (EditText) findViewById(R.id.phone3);

		Button register = (Button) findViewById(R.id.register);
		register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final String loginName = account.getText().toString();
				final String loginPassword = password.getText().toString();
				final String surePassword = sure_password.getText().toString();
				final String realName = realname.getText().toString();
				final String cellphone1 = phone1.getText().toString();
				final String cellphone2 = phone2.getText().toString();
				final String cellphone3 = phone3.getText().toString();

				/**
				 * loading...
				 */

				if (dialog == null) {
					dialog = new ProgressDialog(ResignActivity.this);
				}
				dialog.setTitle("请等待");
				dialog.setMessage("注册中...");
				dialog.setCancelable(false);
				dialog.show();

				/**
				 * 子线程
				 */
				Thread thread = new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							userService.userResign(loginName, loginPassword,
									surePassword, realName, cellphone1,
									cellphone2, cellphone3);
							handler.sendEmptyMessage(FLAG_RESIGN_SUCCESS);
						} catch (ConnectTimeoutException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", MSG_SERVER_TIMEOUT);
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (SocketTimeoutException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg",
									MSG_RESPONCE_TIMEOUT);
							msg.setData(data);
							handler.sendMessage(msg); 
						}catch (ServiceRulesException e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", e.getMessage());
							msg.setData(data);
							handler.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
							Message msg = new Message();
							Bundle data = new Bundle();
							data.putSerializable("ErrorMsg", MSG_RESIGN_ERROR);
							msg.setData(data);
							handler.sendMessage(msg);
						}
					}
				});
				thread.start();
			}
		});
	}

	private void showTip(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		if (str == MSG_RESIGN_SUCCESS) {
			Intent intent = new Intent(ResignActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	private static class IHandler extends Handler {

		private final WeakReference<ActionBarActivity> mActivity;

		public IHandler(ResignActivity activity) {
			mActivity = new WeakReference<ActionBarActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {

			if (dialog != null) {
				dialog.dismiss();
			}

			int flag = msg.what;
			switch (flag) {
			case 0:
				String errorMsg = (String) msg.getData().getSerializable(
						"ErrorMsg");
				((ResignActivity) mActivity.get()).showTip(errorMsg);
				break;
			case FLAG_RESIGN_SUCCESS:
				((ResignActivity) mActivity.get()).showTip(MSG_RESIGN_SUCCESS);
				break;

			default:
				break;
			}
		}
	}

	private IHandler handler = new IHandler(this);

}

  

ServiceRulesException 异常类:
package com.example.loginconnect.service;

public class ServiceRulesException extends Exception {

	/**
	 * 抛异常
	 */
	private static final long serialVersionUID = -4213152538874245667L;
	
	public ServiceRulesException(String message){
		super(message);
	}

}

  布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:background="@drawable/background_login">

    <LinearLayout
        android:id="@+id/loginPanel"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@drawable/background_login_div"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="为您的出行提供保障" 
            android:layout_marginTop="15dp"
            android:textSize="25dp"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:text="请先登录" />

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="15dp"
            android:singleLine="true"
            android:background="@drawable/qq_edit_login"
            android:hint="请输入您的用户名"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="15dp"
            android:singleLine="true"
            android:password="true"
            android:background="@drawable/qq_edit_login"
            android:hint="请输入您的密码"
            android:ems="10" />

        <Button
            android:id="@+id/login"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="18dp"
            android:text="登陆" 
            android:background="@drawable/background_button_div"/>
        

    </LinearLayout>

     <Button
         android:id="@+id/resign"
         android:layout_width="150dp"
         android:layout_height="wrap_content"
         android:layout_alignRight="@+id/loginPanel"
         android:layout_below="@+id/loginPanel"
         android:layout_marginTop="18dp"
         android:background="@drawable/background_button_div"
         android:text="快速注册" />

     <TextView
         android:id="@+id/textView3"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignBaseline="@+id/resign"
         android:layout_alignBottom="@+id/resign"
         android:layout_toLeftOf="@+id/resign"
         android:text="没有账号?请先注册" />

</RelativeLayout>

服务器端:

 

package com.login;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.json.JSONException;
import org.json.JSONObject;

import com.dao.JdbcConnect;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletRequestAware,
        ServletResponseAware {

    private static final long serialVersionUID = 1L;

    HttpServletRequest request;
    HttpServletResponse response;

    private String username;
    private String password;
    private String realname;
    private String cellphone1;
    private String cellphone2;
    private String cellphone3;

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void insert() throws SQLException, IOException,
            ClassNotFoundException {
        this.response.setContentType("text/html;charset=utf-8");
        this.response.setCharacterEncoding("UTF-8");
        String key = this.request.getParameter("json").toString();
        System.out.println(key);
        try {
            JSONObject obj = new JSONObject(key);
            username = obj.getString("username");
            password = obj.getString("password");

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

        // 测试
        // System.out.println(username + "  " + password);
        JdbcConnect.getConnection();
        String sql = "select * from userinfo where username='" + username
                + "' and password ='" + password + "'";
        ResultSet rS = JdbcConnect.executeQuery(sql);
        // 测试
        System.out.println(username + "  " + password);

        try {
            JSONObject obj2 = new JSONObject();
            JSONObject result = new JSONObject();
            // PrintWriter out = response.getWriter();
            if (rS.next()) {
                obj2.put("result", "success");
                result.put("json", obj2);
                response.getWriter().write(result.toString());
                // out.print("success");
                System.out.println(result);
            } else {
                obj2.put("result", "failed");
                result.put("json", obj2);
                response.getWriter().write(result.toString());
                // out.print("failed");
                System.out.println(result);
            }
            // if (out != null) {
            // out.close();
            // }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void regist() throws SQLException, IOException,
            ClassNotFoundException {
        JdbcConnect.getConnection();
        this.response.setContentType("text/html;charset=utf-8");
        this.response.setCharacterEncoding("UTF-8");
        this.request.setCharacterEncoding("UTF-8");
        String key = this.request.getParameter("json").toString();
        System.out.println(key);
        try {
            JSONObject obj = new JSONObject(key);
            username = obj.getString("username");
            password = obj.getString("password");
            realname = obj.getString("realname");
            cellphone1 = obj.getString("cellphone1");
            cellphone2 = obj.getString("cellphone2");
            cellphone3 = obj.getString("cellphone3");

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // username = this.request.getParameter("username");
        // password = this.request.getParameter("password");
        // realname = this.request.getParameter("realname");
        // cellphone1 = this.request.getParameter("cellphone1");
        // cellphone2 = this.request.getParameter("cellphone2");
        // cellphone3 = this.request.getParameter("cellphone3");
        if (username == null && password == null && realname == null
                && cellphone1 == null) {
            throw new IOException();
        }
        System.out.println(username + "  " + password);
        String sql = "insert into userinfo(username,password,realname,cellphone1,cellphone2,cellphone3) values('"
                + username
                + "','"
                + password
                + "','"
                + realname
                + "','"
                + cellphone1 + "','" + cellphone2 + "','" + cellphone3 + "')";
        int flag = JdbcConnect.executeUpdate(sql);
        JSONObject obj2 = new JSONObject();
        JSONObject result = new JSONObject();
        // PrintWriter out = response.getWriter();
        try {
            if (flag > -1) {
                obj2.put("result", "success");
                result.put("json", obj2);
                response.getWriter().write(result.toString());
                System.out.println(result);
            } else {
                obj2.put("result", "failed");
                result.put("json", obj2);
                response.getWriter().write(result.toString());
                System.out.println(result);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // if (out != null) {
        // out.close();
        // }
    }

    public void selectUser() throws SQLException, IOException,
            ClassNotFoundException {
        this.response.setContentType("text/html;charset=utf-8");
        this.response.setCharacterEncoding("UTF-8");
        String key = this.request.getParameter("json").toString();
        try {
            JSONObject obj3 = new JSONObject(key);
            username = obj3.getString("username");

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

        ResultSet rs = null;
        String sql = "select * from userinfo where username='" + username + "'";
        try {
            JdbcConnect.getConnection();
            rs = JdbcConnect.executeQuery(sql);
            if (rs.next()) {
                JSONObject user = new JSONObject();
                user.put("username", rs.getString("username"));
                user.put("realname", rs.getString("realname"));
                user.put("cellphone1", rs.getString("cellphone1"));
                user.put("cellphone2", rs.getString("cellphone2"));
                user.put("cellphone3", rs.getString("cellphone3"));
                JSONObject tem = new JSONObject();
                JSONObject temp = new JSONObject();
                tem.put("user", user);
                temp.put("json", tem);
                response.getWriter().write(temp.toString());
                System.out.println(user);
                System.out.println(temp);
            } else {

            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

 

posted @ 2016-02-01 19:52  华不摇曳  阅读(733)  评论(0编辑  收藏  举报