Android——Tomcat+MySQL+Servlet,實現將Client傳入的數據寫入MySQL


Android客戶端將用戶的注冊信息上傳到Tomcat Web服務器,Servlet將注冊信息寫入到MySQL中。

1,准備工作

(1)在MySQL中創建好要使用的數據庫和數據表。

(2)設置好Tomcat的數據庫連接池。

參見Tomcat數據庫連接池配置


2,Android客戶端Activity和Layout的設計

(1)一個簡單的注冊界面,sign_layout.xml

這里寫圖片描述

sign_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:background="#ff6699cc"
android:orientation="vertical"
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" >


<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fffffffb"
android:orientation="horizontal"
android:padding="40dp" >


<EditText
android:id="@+id/etSgAccount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp"
android:hint="@string/Account"
android:inputType="textEmailAddress" />


<EditText
android:id="@+id/etSgPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/etSgAccount"
android:layout_marginBottom="20dp"
android:hint="@string/Password"
android:inputType="textPassword" />

<EditText
android:id="@+id/etSgRePassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/etSgPassword"
android:layout_marginBottom="20dp"
android:hint="@string/repassword"
android:inputType="textPassword" />



<Button
android:id="@+id/btnSign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/etSgRePassword"
android:background="#ff6699cc"
android:onClick="onLogin"
android:text="@string/signup"
android:textColor="#ffffffff"
android:textSize="24sp" />

</RelativeLayout>

</LinearLayout>

(2)編寫對應的Activity——SignActivity.java

package com.bnutalk.activitytest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SignActivity extends Activity {
private EditText username;
private EditText password;
private Button signup;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_layout);
username=(EditText) findViewById(R.id.etSgAccount);
password=(EditText) findViewById(R.id.etSgPassword);
signup=(Button) findViewById(R.id.btnSign);
}
/*發起HTTP請求*/
public void onLogin(View v)
{
String url="http://172.22.140.237:8080/web/MysServlet";
new HttpThread(url, username.getText().toString(), password.getText().toString()).start();
}

}

其中的重要代碼是函數onLogin,它表示當按下Signup按鈕時,啟動Http線程,向服務器發起Http請求。

/*發起HTTP請求*/
public void onLogin(View v)
{
/*url要訪問的Tomcat的Servlet地址,將ip換成Tomacat所在主機的ip*/
String url="http://172.22.140.237:8080/web/MysServlet";

/*調用訪問網絡的HttpThread*/
new HttpThread(url, username.getText().toString(), password.getText().toString()).start();
}

(3)新建一個Tread類——HttpTread

訪問網絡屬於耗時操作,因此用一個單獨的線程來實現。

package com.bnutalk.activitytest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.string;

public class HttpThread extends Thread {
String url;
String username;
String password;

public HttpThread(String url, String username, String password) {
// TODO Auto-generated constructor stub
this.url = url;
this.username = username;
this.password = password;
}

private void doGet() throws IOException {
/*將username和password傳給Tomcat服務器*/
url=url+"?username="+username+"&password="+password;
try {
URL httpUrl = new URL(url);
/*獲取網絡連接*/
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
/*設置請求方法為GET方法*/
conn.setRequestMethod("GET");
/*設置訪問超時時間*/
conn.setReadTimeout(5000);
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer sb=new StringBuffer();
//讀取服務器返回的信息
while((str=reader.readLine())!=null)
{
sb.append(str);
}
//把服務端返回的數據打印出來
System.out.println("result"+sb.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

/*在run中調用doGet*/
@Override
public void run() {
try {
doGet();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

(4)在AndroidManifest.xml中添加網絡訪問權限

<uses-permission android:name="android.permission.INTERNET"/>

如圖:
這里寫圖片描述


3,Server和Servlet設置

(1)建立好一個server和一個web項目,在web下建立所需的Servlet

這里寫圖片描述
如圖所示,注冊用到的Servlet是MyServlet.java,請忽略LogServlet.java

(2)在web.xml中注冊Servlet

<servlet>
<servlet-name>DataServiceServlet</servlet-name>
<servlet-class>com.imooc.servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServiceServlet</servlet-name>
<url-pattern>/DataServiceServlet</url-pattern>
</servlet-mapping>

如圖所示:
這里寫圖片描述

(3)編寫MyServlet.java

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.catalina.Context;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

/**
* Servlet implementation class MyServlet
*/

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/

public MyServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*獲取請求的數據,並向控制台輸出*/
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
System.out.println("username" + "," + username);
System.out.println("password" + "," + password);

int rs ;
String sql = "insert into bnutalk(id,username,psswd) values(3,?,?)";

/*實現向MySQL中插入username和password*/
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/t1");
/*獲得數據庫的連接*/
java.sql.Connection conn =ds.getConnection();
conn = ds.getConnection();
/*執行sql*/
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs= ps.executeUpdate();
} catch (SQLException se) {
System.out.println("SQLException: " + se.getMessage());
} catch (NamingException ne) {
System.out.println("NamingException: " + ne.getMessage());
}
}
}

4,運行

(1)運行web項目,run on server

這里寫圖片描述

(2)運行Android客戶端

如圖:
這里寫圖片描述


先看看此時數據表中的內容:
這里寫圖片描述


(3)注冊一個用戶

用戶名和密碼都是csdn
這里寫圖片描述


控制台輸出:
這里寫圖片描述


再次查看數據表:
這里寫圖片描述

如果有看不懂的,可以先去補一補Servlet,Tomcat數據庫連接池,MySQL,Thread這些基礎知識,有個大概印象,最起碼能知道其中的邏輯,大體框架,實現機制。腦海中一個框架圖,再來看代碼就很簡單了。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com