版權聲明:http://www.cnblogs.com/gis-laozhang/p/7079992.htmlhtml
----------------------------------------------------------------------------------------------------前端
需求:Android客戶端鏈接服務器端mysql數據庫中的內容java
環境部署mysql
服務器:apache-tomcat-8.5.9web
語言版本:Java 1.8.0_101sql
編譯環境:Eclipse數據庫
Android Studioapache
調用jar包:httpclient-4.2.5,httpcore-4.2.4 //HttpClient父類tomcat
mysql-connector-java-5.1.40-bin //用於鏈接mysql數據庫服務器
思路:涉及到服務器端mysql數據庫安裝、web應用部分開發和Android客戶端開發三個部分
步驟:
一、mysql數據庫安裝
a、先安裝mysql-installer-community-5.7.17.0,其中在Setup Type上選擇「Server only」,而後記住數據庫端口號和帳號(例如:root)密碼(例如:123456),以下圖:
b、安裝成功驗證。命令行窗口輸入密碼,而後輸入顯示全部數據庫命令:show databases; 必定要有分號,並按回車。
c、NavicatforMySQL下載及使用。註冊,而後鏈接數據庫,輸入密碼後,可以看到已存在的數據庫,能夠在其中進行相關數據庫和數據表的建立操做。
(具體以參考資料中的內容爲主)
二、web應用部分開發
a、新建servlet,而且配置好web.xml中的相應信息(在WebContent下的WEB-INF文件夾下加入web.xml文件來鏈接servlet與jsp前端),此外還需在libs中添加mysql-connector-java-5.1.37-bin.jar文件,代碼以下:
1 package com.Servlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 import java.io.PrintWriter; 11 import java.sql.Connection; 12 import java.sql.ResultSet; 13 import java.sql.Statement; 14 import com.DBTool.DBUtil; 15 16 @WebServlet("/Servlet") 17 public class Login extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public Login() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 /** 28 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 29 */ 30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 // TODO Auto-generated method stub 32 response.getWriter().append("Served at: ").append(request.getContextPath()); 33 } 34 35 /** 36 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 37 */ 38 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 String ID = request.getParameter("ID"); 40 String PW= request.getParameter("PW"); 41 boolean type=false; 42 response.setContentType("text/html; charset=UTF-8"); 43 PrintWriter out = response.getWriter(); 44 try 45 { 46 Connection con=DBUtil.getConnection(); 47 Statement stmt=con.createStatement(); 48 //mysql數據庫中的數據表,表名叫:demotable ,須要本身預先在數據庫中進行建立,包含相應的字段和記錄。 49 String sql="select * from mysql.demotable where uid="+ID+" and pwd="+PW; 50 ResultSet rs=stmt.executeQuery(sql); 51 while(rs.next()) 52 { 53 type=true; 54 } 55 } 56 catch(Exception ex) 57 { 58 ex.printStackTrace(); 59 } 60 finally 61 { 62 DBUtil.Close(); 63 out.print(type); 64 out.flush(); 65 out.close(); 66 } 67 } 68 69 }
web.xml內容以下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 3 <display-name>web</display-name> 4 <servlet> 5 <display-name>Login</display-name> 6 <servlet-name>Login</servlet-name> 7 <servlet-class>com.Servlet.Login</servlet-class> 8 </servlet> 9 <servlet-mapping> 10 <servlet-name>Login</servlet-name> 11 <url-pattern>/Login</url-pattern> 12 </servlet-mapping> 13 <welcome-file-list> 14 <welcome-file>index.html</welcome-file> 15 <welcome-file>index.jsp</welcome-file> 16 </welcome-file-list> 17 </web-app>
b、前端界面設計(TestPage.jsp)以下:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 3 <html> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 6 <title>Insert title here</title> 7 </head> 8 <body> 9 <form id="from1" action="Login" method="post"> 10 <table> 11 <tr><td>用戶名</td><td><input type="text" name="ID"></td></tr> 12 <tr><td>密碼</td><td><input type="password" name="PW"></td></tr> 13 <tr><td colspan="2" align="center"><input type="submit" value="登錄"/></td></tr> 14 </table> 15 </form> 16 </body> 17 </html>
c、在java Resources下的src文件夾中新建com.DBTool包,用做數據池來鏈接數據庫,在包中創建DBUtil類實現功能,代碼以下:
1 package com.DBTool; 2 3 4 import java.sql.*; 5 6 public class DBUtil { 7 //其中mysql是數據庫名稱,在mysql57版本的數據庫中已經預先新建完成;3306是mysql數據庫的端口號。 8 private static String url="jdbc:mysql://localhost:3306/mysql"; 9 //com.mysql.jdbc.Driver是mysql-connector-java-5.1.40中的驅動包路徑 10 private static String driverClass="com.mysql.jdbc.Driver"; 11 //mysql的帳號和密碼是在安裝mysql中進行設置的,這裏拿來用便可。 12 private static String username="root"; 13 private static String password="123456"; 14 private static Connection conn; 15 //裝載驅動 16 static{ 17 try{ 18 Class.forName(driverClass); 19 } 20 catch(ClassNotFoundException e){ 21 e.printStackTrace(); 22 } 23 } 24 //獲取數據庫鏈接 25 public static Connection getConnection(){ 26 try{ 27 conn=DriverManager.getConnection(url,username,password); 28 } 29 catch(SQLException e){ 30 e.printStackTrace(); 31 } 32 return conn; 33 } 34 //創建數據庫鏈接 35 public static void main(String[] args){ 36 Connection conn=DBUtil.getConnection(); 37 if(conn!=null){ 38 System.out.println("數據庫鏈接成功"); 39 } 40 else{ 41 System.out.println("數據庫鏈接失敗"); 42 } 43 } 44 //關閉數據庫鏈接 45 public static void Close(){ 46 if(conn!=null){ 47 try{ 48 conn.close(); 49 } 50 catch(SQLException e){ 51 e.printStackTrace(); 52 } 53 } 54 } 55 }
d、運行服務器,測試是否成功搭建。
三、Android部分開發
僅附上核心部分代碼,以下:
1 public void SendByHttpClient(final String id, final String pw){ 2 new Thread(new Runnable() { 3 @Override 4 public void run() { 5 try { 6 HttpClient httpclient=new DefaultHttpClient(); 7 HttpPost httpPost=new HttpPost("http://web應用部署服務器上的IP地址:8080/HttpClientDemo/Login");//服務器地址,指向Servlet 8 List<NameValuePair> params=new ArrayList<NameValuePair>();//將id和pw裝入list 9 params.add(new BasicNameValuePair("ID",id)); 10 params.add(new BasicNameValuePair("PW",pw)); 11 final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");//以UTF-8格式發送 12 httpPost.setEntity(entity); 13 HttpResponse httpResponse= httpclient.execute(httpPost); 14 if(httpResponse.getStatusLine().getStatusCode()==200)//在200毫秒以內接收到返回值 15 { 16 HttpEntity entity1=httpResponse.getEntity(); 17 String response=EntityUtils.toString(entity1, "utf-8");//以UTF-8格式解析 18 Message message=new Message(); 19 message.what=USER_LOGIN; 20 message.obj=response; 21 handler.sendMessage(message);使用Message傳遞消息給線程 22 } 23 } 24 catch (Exception e) { 25 e.printStackTrace(); 26 } 27 } 28 }).start(); 29 }
最終,測試結果圖,以下:
-------------------------------------------------------------------------------------------
參考資料:
http://transcoder.tradaquan.com/from=1017649e/bd_page_type=1/ssid=0/uid=0/pu=usm%401%2Csz%401320_2001%2Cta%40iphone_1_9.2_3_601/baiduid=3B77D44CFFB44688FD602EAD8A663022/w=0_10_/t=iphone/l=3/tc?ref=www_iphone&lid=9684581900815139314&order=2&fm=alhm&h5ad=1&srd=1&dict=32&tj=h5_mobile_2_0_10_title&w_qd=IlPT2AEptyoA_ykzv39b7vOxASxPcYSfDwWEKKelwb6TYslhS_&sec=22021&di=4d89010ccd0ca0f7&bdenc=1&tch=124.133.103.675.1.561&nsrc=IlPT2AEptyoA_yixCFOxXnANedT62v3IEQGG_ytK1DK6mlrte4viZQRAUSD8L7qYZpPPtCPQpxkCwnWh_7YskNYWgK&eqid=86668bed7c43800010000003594fbeac&wd=&clk_info=%7B%22srcid%22%3A%221599%22%2C%22tplname%22%3A%22h5_mobile%22%2C%22t%22%3A1498398423079%2C%22sig%22%3A%2242687%22%2C%22xpath%22%3A%22div-a-h3%22%7D
http://blog.csdn.net/qq_14923661/article/details/50461696 // Android平臺實現與Apache Tomcat服務器數據交互(MySql數據庫)