原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原創地址 、作者信息和本聲明。http://www.cnblogs.com/zhu520/p/7724524.html
經過兩天的時間我終於把Android studio與eclipse和mysql進行了鏈接!!!因為是自學,哪個大神看到有問題指點一下。
一:eclipse的配置
服務器:配置你的項目的tomca
tomcat弄好之后不要着急點擊 完成, 點擊 下一步
不要着急點擊 完成, 點擊 下一步
你也可不改,對比一下差別:
需要的jar包
MySQL創建數據庫和表
創建數據庫
create database printing character set utf8 collate utf8_general_ci;
創建表:
use jdbc01;
create table sys_staff (
StaffID int primary key auto_increment,
Account varchar(40),
Password varchar(40)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
表創建好之后,給一條數據 。
我給賬號和密碼都為111
二:代碼
1): eclipse與MySQL的鏈接
ToolMySQLConnection類

package zhu.printing.unit; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ToolMySQLConnection { public static final String URL="jdbc:mysql://localhost:3306/printing"; public static final String NAME = "root"; public static final String PASSWORD = "root"; public static final String DREIVER = "com.mysql.jdbc.Driver"; static { try { //加載驅動器 Class.forName(DREIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { try { return DriverManager.getConnection(URL, NAME, PASSWORD);//創建與數據庫的鏈接 } catch (SQLException e) { e.printStackTrace(); } return null; } //設置一個公共的關閉鏈接、釋放資源的方法 . 因為每次只要進行了增,刪,查,改 之后 都必須要 事件, 那么就設置一個公共的方法 //而關閉資源要從 ResultSet先關閉-->,再到 PreparedStatement-->,最后到 Connection關閉 public static void Close(ResultSet rs, PreparedStatement ps, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2):創建Servlet的類

package zhu.printing.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import zhu.printing.unit.ToolMySQLConnection; public class LoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ID = request.getParameter("ID"); //用於接收android前台的輸入的值,此處參數必須要與你前台的值相對應 String PW= request.getParameter("PW"); boolean type=false;//用於判斷賬號和密碼是否與數據庫中查詢結果一致 response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); Connection con=null; JSONObject json = new JSONObject(); // JsonConfig jsonConfig = new JsonConfig(); // jsonConfig.registerJsonValueProcessor(java.sql.Date.class,new JsonDateValueProcessor()); try { con=ToolMySQLConnection.getConnection(); Statement stmt=con.createStatement(); String sql="select * from printing.sys_staff where Account="+ID+" and Password="+PW; ResultSet rs=stmt.executeQuery(sql); while(rs.next()) { type=true; } } catch(Exception ex) { ex.printStackTrace(); } finally { ToolMySQLConnection.Close(null, null, con); json.put("msg", type ); //json.put("msg", JSONArray.fromObject(type,jsonConfig)); response.getWriter().write(json.toString()); out.flush(); out.close(); } } }
3):配置servlet
去WEB-INF文件夾下的web.xml配置剛剛新建的LoginServlet

<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>zhu.printing.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/zhu/LoginServlet</url-pattern> </servlet-mapping>
4):創建jsp
Test1.jsp的代碼

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!-- c標簽要使用,那么就必須要有它 ${pageContext.request.contextPath}--> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set scope="page" var="url" value="${pageContext.request.contextPath }"></c:set> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'MyJsp.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action=" ${url}/zhu/LoginServlet" method="post"> <table> <tr><td>用戶名</td><td><input type="text" name="ID"></td></tr> <tr><td>密碼</td><td><input type="text" name="PW"></td></tr> <tr><td colspan="2" align="center"><input type="submit" value="登陸"></td></tr> </table> </form> </body> </html>
5):運行
我把數據設置為json的格式,因為這樣容易在Android studio那邊獲取數據,
二:Android studio
代碼
1):創建一個a_login.xml文件

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="zhu.com.printitem.LoginActivity" android:background="@drawable/background_login"> <RelativeLayout android:id="@+id/kj_ct" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dip" android:layout_marginRight="15dip" android:layout_marginTop="120dip" android:background="@drawable/background_login_radius" android:padding="15dip"> <!-- 賬號 --> <TextView android:id="@+id/kj_accountnumber_lb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="5dp" android:text="賬號" /> <EditText android:id="@+id/kj_accountnumber_edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/kj_accountnumber_lb" android:hint=" " android:inputType="text" android:singleLine="true" /> <!-- 密碼 text --> <TextView android:id="@+id/kj_password_lb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/kj_accountnumber_edittext" android:layout_marginTop="3dp" android:text="密碼" /> <EditText android:id="@+id/kj_password_edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/kj_password_lb" android:hint="請輸入賬號" android:inputType="textPassword" /> <Button android:id="@+id/kj_register_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/kj_password_edittext" android:text="注冊" /> <!-- 登錄button --> <Button android:id="@+id/kj_login_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@id/kj_password_edittext" android:layout_below="@id/kj_password_edittext" android:text="登陸" /> </RelativeLayout> </RelativeLayout>
2):創建一個HttpUtil類
==》這個類 我是看這個文章的 http://blog.csdn.net/wangwei_cq/article/details/9453345

package zhu.com.printitem.util; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.BinaryHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; /** * Created by XiaoZhu on 2017/10/24. */ public class HttpUtil { //實例話對象 private static AsyncHttpClient client =new AsyncHttpClient(); static { client.setTimeout(11000); //設置鏈接超時,如果不設置,默認為10s } //用一個完整url獲取一個string對象 public static void get(String urlString,AsyncHttpResponseHandler res) { client.get(urlString, res); } //url里面帶參數 public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) { client.get(urlString, params,res); } //不帶參數,獲取json對象或者數組() public static void get(String urlString,JsonHttpResponseHandler res) { client.get(urlString,res); } //帶參數,獲取json對象或者數組() public static void get(String urlString,RequestParams params,JsonHttpResponseHandler res) { client.get(urlString, params,res); } //下載數據使用,會返回byte數據 public static void get( String uString, BinaryHttpResponseHandler bHandler) { client.get(uString, bHandler); } public static AsyncHttpClient getClient() { return client; } }
3):登錄界面LoginActivity類

package zhu.com.printitem; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONException; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import zhu.com.printitem.util.HttpUtil; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { Button btn_login,btn_register; EditText et_accountnumber,et_passwrod; AsyncHttpClient m_HttpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a_login); m_HttpClient = new AsyncHttpClient(); btn_login= (Button) findViewById(R.id.kj_login_btn); btn_register= (Button) findViewById(R.id.kj_register_btn); et_accountnumber= (EditText) findViewById(R.id.kj_accountnumber_edittext); et_passwrod= (EditText) findViewById(R.id.kj_password_edittext); btn_login.setOnClickListener(this); btn_register.setOnClickListener(this); } public void connectionURL(String id, String pw){ /*這里192.168.191.2==》表示你當前使用的網絡ip,還有如果是真機運行那么手機必須要鏈接你自個的電腦的wifi,這樣才能保證在同一個網絡ID地址 * 171023_printting==》你在eclipse創建的項目名稱 * zhu/LoginServlet==》表示在eclipse的web.xml配置servlet的地址 * */ String url="http://192.168.191.2:8080/171023_printting/zhu/LoginServlet"; RequestParams params = new RequestParams(); // 綁定參數 params.put("ID",id); params.put("PW",pw); HttpUtil.get(url,params,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { if (statusCode==200){ try { if(response.getBoolean("msg")==true){ Toast.makeText(LoginActivity.this, "登錄成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(LoginActivity.this, "登錄失敗!", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); } @Override public void onClick(View v) { switch (v.getId()) { //登陸 case R.id.kj_login_btn: Intent it0=new Intent(); it0.setClass(LoginActivity.this,MainInterfaceActivity.class); String uid=et_accountnumber.getText().toString().trim(); String pw=et_passwrod.getText().toString().trim(); connectionURL(uid,pw); // startActivity(it0); break; case R.id.kj_register_btn: Intent it=new Intent(); it.setClass(LoginActivity.this,RegisterActivity.class); startActivity(it); break; } ; } } //子進程 /* new Thread(new Runnable() { @Override public void run() { } }).start();*/ /* HttpUtil.get(url,params, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { JSONObject jsonObject = new JSONObject(new String(responseBody)); JSONArray jsonArray = jsonObject.getJSONArray("msg"); Log.v("Code",jsonArray+""); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(LoginActivity.this, "鏈接eclipse失敗", Toast.LENGTH_SHORT).show(); } }); * */
4):運行Android studio之前必須要運行eclipse的項目
源碼:http://pan.baidu.com/s/1bppnmLT