Home  >  Article  >  Database  >  利用简易Tomcat服务器结合MysqL实现Android手机注册与登录(客户_MySQL

利用简易Tomcat服务器结合MysqL实现Android手机注册与登录(客户_MySQL

WBOY
WBOYOriginal
2016-06-01 13:11:272253browse

AndroidTomcat

package com.example.java4androidmysql;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;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.conn.params.ConnManagerParams;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 android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {	public static final String URL = "http://192.168.2.1:8080/JavaRegisterMysql/login";		public static String res="";    public static String name = "";    public static String code = "";    public static String phone =" ";    public static String chose="0";	Button connectButton=null;	Button registerButton=null;	EditText noteUser=null;	EditText notePassword=null;			@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		requestWindowFeature(Window.FEATURE_NO_TITLE);		setContentView(R.layout.activity_main);						connectButton=(Button)findViewById(R.id.btnConnect);		registerButton=(Button)findViewById(R.id.btnRegister);        noteUser=(EditText)findViewById(R.id.editUserName);        notePassword=(EditText)findViewById(R.id.editPassword);        //////注意类Class DriverManager Statement ResultSet                        connectButton.setOnClickListener(new View.OnClickListener() {						public void onClick(View v) {									        			            Toast.makeText(MainActivity.this, "正在登录", Toast.LENGTH_SHORT).show();			            name = noteUser.getText().toString().trim();			            code = notePassword.getText().toString().trim();    			            chose="1";			            new SubmitAsyncTask().execute(URL);			            			            Toast.makeText(MainActivity.this, "res = "+res, Toast.LENGTH_SHORT).show();			            if(res.equals("2")){			            	Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();			    			//Intent intent=new Intent();			    			//intent.setClass(MainActivity.this, WriteNote.class);			    			//MainActivity.this.startActivity(intent);			            }else if(res.equals("1")){			            	Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();			            }else if(res.equals("3")){			            	Toast.makeText(MainActivity.this, "注册失败", Toast.LENGTH_SHORT).show();			            }else if(res.equals("4")){			            	Toast.makeText(MainActivity.this, "注册成功", Toast.LENGTH_SHORT).show();			            }else if(res.equals("-1")){			            	Toast.makeText(MainActivity.this, "网络异常", Toast.LENGTH_SHORT).show();			            }					}				});        noteUser.setText("ab");        notePassword.setText("123456");        		registerButton.setOnClickListener(new View.OnClickListener() {						public void onClick(View v) {									            						Intent intent=new Intent();						intent.setClass(MainActivity.this, Register.class);						MainActivity.this.startActivity(intent);			                									}				});	    	}			@Override	public boolean onCreateOptionsMenu(Menu menu) {		// Inflate the menu; this adds items to the action bar if it is present.		getMenuInflater().inflate(R.menu.main, menu);		return true;	}			}

以上为手机主界面函数调用

package com.example.java4androidmysql;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class Register extends Activity{	public static final String URL = "http://192.168.2.1:8080/JavaRegisterMysql/login";	Button backButton=null;	Button registerButton=null;	EditText user=null;	EditText password=null;	EditText phone=null;	@Override	protected void onCreate(Bundle savedInstanceState) {		// TODO Auto-generated method stub		super.onCreate(savedInstanceState);		requestWindowFeature(Window.FEATURE_NO_TITLE);		setContentView(R.layout.register);				backButton=(Button)findViewById(R.id.btnBack);		registerButton=(Button)findViewById(R.id.btnRegister);        user=(EditText)findViewById(R.id.editUserName);        password=(EditText)findViewById(R.id.editPassword);        phone=(EditText)findViewById(R.id.editPhone);        //////注意类Class DriverManager Statement ResultSet                        registerButton.setOnClickListener(new View.OnClickListener() {						public void onClick(View v) {									            			            MainActivity.name = user.getText().toString().trim();			            MainActivity.code = password.getText().toString().trim();			            MainActivity.phone = phone.getText().toString().trim();			            MainActivity.chose="2";			            			            new SubmitAsyncTask().execute(URL);			         			            Toast.makeText(Register.this, "res = "+MainActivity.res, Toast.LENGTH_SHORT).show();			            if(MainActivity.res.equals("2")){			            	Toast.makeText(Register.this, "登录成功", Toast.LENGTH_SHORT).show();			    			//Intent intent=new Intent();			    			//intent.setClass(MainActivity.this, WriteNote.class);			    			//MainActivity.this.startActivity(intent);			            }else if(MainActivity.res.equals("1")){			            	Toast.makeText(Register.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();			            }else if(MainActivity.res.equals("3")){			            	Toast.makeText(Register.this, "注册失败", Toast.LENGTH_SHORT).show();			            }else if(MainActivity.res.equals("4")){			            	Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();			            }else if(MainActivity.res.equals("-1")){			            	Toast.makeText(Register.this, "网络异常", Toast.LENGTH_SHORT).show();			            }			                									}				});        user.setText("gjw");        password.setText("123");        phone.setText("13570236302");	}}

以上为注册界面

package com.example.java4androidmysql;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;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.conn.params.ConnManagerParams;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 android.os.AsyncTask;public class SubmitAsyncTask extends AsyncTask<String, Integer, String>{    String info = "";    protected String doInBackground(String... params) {        // TODO Auto-generated method stub        String url = params[0];        String reps = "";                    reps = doPost(url);        return reps;    }    protected void onPostExecute(String result) {        // TODO Auto-generated method stub        MainActivity.res = result.trim();        super.onPostExecute(result);    }     /** * 用Post方式跟服务器传递数据 * @param url * @return */private String doPost(String url){    String responseStr = "";    try {    	//发送post类型请求        HttpPost httpRequest = new HttpPost(url);        HttpParams params = new BasicHttpParams();        ConnManagerParams.setTimeout(params, 1000); //从连接池中获取连接的超时时间        HttpConnectionParams.setConnectionTimeout(params, 3000);//通过网络与服务器建立连接的超时时间        HttpConnectionParams.setSoTimeout(params, 5000);//读响应数据的超时时间        httpRequest.setParams(params);                //下面开始跟服务器传递数据,使用BasicNameValuePair        List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();                paramsList.add(new BasicNameValuePair("NAME", MainActivity.name));        paramsList.add(new BasicNameValuePair("CODE", MainActivity.code));        paramsList.add(new BasicNameValuePair("PHONE", MainActivity.phone));        paramsList.add(new BasicNameValuePair("CHOSE", MainActivity.chose));                UrlEncodedFormEntity mUrlEncodeFormEntity = new UrlEncodedFormEntity(paramsList, HTTP.UTF_8);        httpRequest.setEntity(mUrlEncodeFormEntity);                ////////////////////////////////////////////////        HttpClient httpClient = new DefaultHttpClient();        HttpResponse httpResponse = httpClient.execute(httpRequest);        final int ret = httpResponse.getStatusLine().getStatusCode();        if(ret == HttpStatus.SC_OK){            responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);        }else{            responseStr = "-1";        }        } catch (UnsupportedEncodingException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }         return responseStr;	}}

以上为接口类,但写得可能有些不对(如返回变量那里是上次调用的),略忙,等再改一下。

<?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"    android:background="@drawable/ab" >    <TextView        android:id="@+id/FRppt01"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/Title"         android:textSize="15pt"        android:textColor="#FFFFFF"        android:textStyle="bold"        android:layout_marginTop="40dp"        android:gravity="center_horizontal"        android:padding="3dip"/>       	<EditText        android:id="@+id/editUserName"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="输入用户名"/>		<EditText        android:id="@+id/editPassword"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="输入密码"/>    	      <TableLayout             android:layout_width="fill_parent"            android:layout_height="fill_parent">            <TableRow>			    <Button			        android:id="@+id/btnConnect"			        android:layout_width="fill_parent"			        android:layout_height="wrap_content"			        android:text="登录"			        android:layout_marginTop="260dp"			       			        android:layout_weight="1" />			    <Button			        android:id="@+id/btnRegister"			        android:layout_width="fill_parent"			        android:layout_height="wrap_content"			        android:text="注册" 			        android:layout_marginTop="260dp"			       			        android:layout_weight="1"/>"		    </TableRow>	     </TableLayout></LinearLayout>

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:background="@drawable/ab" >    <TextView        android:id="@+id/FRppt01"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/RegisterPage"         android:textSize="15pt"        android:textColor="#FFFFFF"        android:textStyle="bold"        android:layout_marginTop="40dp"        android:gravity="center_horizontal"        android:padding="3dip"/>        <TableLayout		android:layout_below="@id/FRppt01" 		android:layout_width="fill_parent"		android:layout_height="wrap_content"		android:stretchColumns="1"		android:layout_marginLeft="10dip"		android:layout_marginRight="10dip"		>		<TableRow 		    android:layout_width="fill_parent"		    android:layout_height="wrap_content"		    android:layout_marginBottom="5dip">    		    <TextView 		        android:id="@+id/textUserName"		        android:layout_width="wrap_content"		        android:layout_height="wrap_content"		        android:textSize="12pt"		        android:layout_weight="1"		        android:layout_below="@id/FRppt01"		        android:text="@string/userName"/>"			<EditText		        android:id="@+id/editUserName"		        android:layout_width="fill_parent"		        android:layout_height="wrap_content"		        android:layout_weight="1"		        />		</TableRow>		<TableRow 		    android:layout_width="fill_parent"		    android:layout_height="wrap_content"		    android:layout_marginBottom="5dip">			<TextView 		        android:id="@+id/textPassword"		        android:layout_width="wrap_content"		        android:layout_height="wrap_content"		        android:layout_weight="1"		        android:textSize="12pt"		        android:text="@string/passWord"/>			<EditText		        android:id="@+id/editPassword"		        android:layout_width="fill_parent"		        android:layout_height="wrap_content"		        android:layout_weight="1"		        />		</TableRow>		<TableRow 		    android:layout_width="fill_parent"		    android:layout_height="wrap_content"		    android:layout_marginBottom="5dip">		    				<TextView 		        android:id="@+id/textPhone"		        android:layout_width="wrap_content"		        android:layout_height="wrap_content"		        android:layout_weight="1"		        android:textSize="12pt"		        android:text="@string/phone"/>			<EditText		        android:id="@+id/editPhone"		        android:layout_width="fill_parent"		        android:layout_height="wrap_content"		        android:layout_weight="1"		        		        />		</TableRow>	</TableLayout>		      <TableLayout             android:layout_width="fill_parent"            android:layout_height="fill_parent"            >          <TableRow>              <Button                  android:id="@+id/btnBack"                  android:layout_width="fill_parent"                  android:layout_height="wrap_content"                  android:layout_marginTop="260dp"                  android:layout_weight="1"                  android:text="@string/Back" />              <Button                  android:id="@+id/btnRegister"                  android:layout_width="fill_parent"                  android:layout_height="wrap_content"                  android:layout_marginTop="260dp"                  android:layout_weight="1"                  android:text="@string/Register" />          </TableRow>	     </TableLayout></RelativeLayout>

以上两段代码为布局文件代码。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn