Android客户端将用户的注册信息上传到Tomcat Web服务器,Servlet将注册信息写入到MySQL中。

1,准备工作

(1)在MySQL中创建好要使用的数据库和数据表。

(2)设置好Tomcat的数据库连接池。

参见Tomcat数据库连接池配置

2,Android客户端Activity和Layout的设计

(1)一个简单的注册界面,sign_layout.xml

Android——Tomcat+MySQL+Servlet,实现将Client传入的数据写入MySQL_第1张图片

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

Android——Tomcat+MySQL+Servlet,实现将Client传入的数据写入MySQL_第2张图片
如图所示,注册用到的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>

如图所示:
Android——Tomcat+MySQL+Servlet,实现将Client传入的数据写入MySQL_第3张图片

(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客户端

如图:

先看看此时数据表中的内容:
Android——Tomcat+MySQL+Servlet,实现将Client传入的数据写入MySQL_第4张图片

(3)注册一个用户

用户名和密码都是csdn

控制台输出:
这里写图片描述

再次查看数据表:

如果有看不懂的,可以先去补一补Servlet,Tomcat数据库连接池,MySQL,Thread这些基础知识,有个大概印象,最起码能知道其中的逻辑,大体框架,实现机制。脑海中一个框架图,再来看代码就很简单了。

更多相关文章

  1. Android数据库加密
  2. Android 数据库SQLite的使用简单Demo
  3. Android获取音视频原始流数据方法详解
  4. Android中数据存储——ContentProvider存储数据
  5. 读取指定路径数据库的方法
  6. Android Message里传送的数据
  7. fanfou(饭否) android客户端 代码学习1
  8. 对android内置的sqlLite数据库进行增、删、改、查操作
  9. android 本地存储数据

随机推荐

  1. 深入理解计算机系统(4.1)------Y86指令集体
  2. [码]值得收藏的好东西
  3. SkyWalking结合Logback获取全局唯一标识
  4. [转载] 王垠: 如何掌握所有的程序语言
  5. SkyWalking 6.x 源码分析 —— 调试环境
  6. ZK Leader选举
  7. 定时删除10天前的Es索引
  8. 分布式日志链路追踪:skywalking + elastic
  9. 什么是垃圾快乐, 以及如何浪费你的时间
  10. 整合SSM框架应用