本例簡單地實現Android客戶端與伺服器端交互,主要是通過客戶端輸入內容(學號)提交到伺服器端,伺服器端與資料庫交互去查詢相應信息(姓名)。根據這個做個完整的安卓登錄是沒問題的。本例資料庫伺服器都採用本地,測試時Android客戶端與服務端在同一網路中! 1、本例演示截圖: 當輸入錯誤的學號(與數 ...
本例簡單地實現Android客戶端與伺服器端交互,主要是通過客戶端輸入內容(學號)提交到伺服器端,伺服器端與資料庫交互去查詢相應信息(姓名)。根據這個做個完整的安卓登錄是沒問題的。本例資料庫伺服器都採用本地,測試時Android客戶端與服務端在同一網路中!
1、本例演示截圖:
當輸入錯誤的學號(與資料庫不匹配),顯示查無此人
當輸入正確的學號時,顯示學號對應的學生姓名:
2、數據模型:
3、客戶端:
本例客戶端發送請求給伺服器端,附帶JSON格式字元串(學號{"stu_number":"123456789"}),當然這是最簡單的JSON格式。
4、伺服器端:(項目目錄)
ConnDb.java:返回連接對象,通過測試類TextConn.java可測試與資料庫連接是否正常。
SearchNameServices.java:業務類、核心類,處理與資料庫交互的邏輯問題,返回從資料庫獲取的結果
SearchServlet.java:servlet類,將客戶端請求的數據返回給客戶端,可以對數據做處理,回傳給客戶端(這裡將獲取的用戶名進行封裝,轉換成JSON格式字元串來傳送)
5、核心代碼
Android客戶端:
MainActivity.java:
Package1 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 2 3 private EditText stu_number, stu_name; 4 private Button btn_search; 5 private OkHttpClient okhttpClient; 6 private String stu_number_txt; 7 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main); 13 initView(); 14 } 15 16 public void initView() { 17 btn_search = (Button) findViewById(R.id.btn_search); 18 stu_number = (EditText) findViewById(R.id.stu_number); 19 stu_name = (EditText) findViewById(R.id.stu_name); 20 btn_search.setOnClickListener(this); 21 } 22 23 @Override 24 public void onClick(View view) { 25 if (view.getId() == R.id.btn_search) { 26 //獲取輸入的學號 27 stu_number_txt = stu_number.getText().toString(); 28 new Thread(new Runnable() { 29 @Override 30 public void run() { 31 sendRequest(stu_number_txt); 32 } 33 }).start(); 34 35 } 36 } 37 38 private void sendRequest(String stu_number_txt) { 39 Map map = new HashMap(); 40 map.put("stu_number", stu_number_txt); 41 JSONObject jsonObject = new JSONObject(map); 42 String jsonString = jsonObject.toString(); 43 // Log.d("這將JSON對象轉換為json字元串", jsonString); 44 RequestBody body = RequestBody.create(null, jsonString);//以字元串方式 45 okhttpClient = new OkHttpClient(); 46 final Request request = new Request.Builder() 47 .url("http://192.168.43.218:8080/AndroidServerDemo/SearchServlet") 48 .post(body) 49 .build(); 50 Call call = okhttpClient.newCall(request); 51 call.enqueue(new Callback() { 52 @Override 53 public void onFailure(Call call, IOException e) { 54 runOnUiThread(new Runnable() { 55 @Override 56 public void run() { 57 Toast.makeText(MainActivity.this, "連接失敗!", Toast.LENGTH_SHORT).show(); 58 } 59 }); 60 e.printStackTrace(); 61 } 62 63 @Override 64 public void onResponse(Call call, Response response) throws IOException { 65 // runOnUiThread(new Runnable() { 66 // @Override 67 // public void run() { 68 // Toast.makeText(MainActivity.this,"連接成功!",Toast.LENGTH_SHORT).show(); 69 // } 70 // }); 71 String res = response.body().string();//獲取到傳過來的字元串 72 try { 73 JSONObject jsonObj = new JSONObject(res); 74 String stu_name = jsonObj.getString("stu_name"); 75 showRequestResult(stu_name); 76 } catch (JSONException e) { 77 e.printStackTrace(); 78 } 79 } 80 }); 81 } 82 83 private void showRequestResult(final String response) { 84 runOnUiThread(new Runnable() { 85 @Override 86 /** 87 * 實時更新,資料庫信息改變時,客戶端內容發生改變 88 */ 89 public void run() { 90 stu_name.setText(response); 91 } 92 }); 93 } 94 }
伺服器端:
ConnDb.java:
1 package com.thanlon.dao; 2 3 import java.sql.*; 4 5 public class ConnDb { 6 private String driverName = "com.mysql.jdbc.Driver"; 7 private String username = "root"; 8 private String password = "123456"; 9 private String url = "jdbc:mysql://localhost:3306/androidDb"; 10 11 public Connection conn() { 12 try { 13 Class.forName(driverName); 14 try { 15 Connection conn = DriverManager.getConnection(url,username,password); 16 return conn; 17 } catch (SQLException e) { 18 // TODO Auto-generated catch block 19 e.printStackTrace(); 20 System.out.println("連接資料庫失敗!"); 21 } 22 } catch (ClassNotFoundException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 System.out.println("載入驅動失敗!"); 26 } 27 return null; 28 } 29 }
TextConn.java:
1 package Test; 2 3 import org.junit.Test; 4 5 import com.thanlon.dao.ConnDb; 6 7 public class TestConn { 8 /** 9 * 測試能否正常連接資料庫 10 */ 11 @Test 12 public void TestConnDb() { 13 ConnDb connDb = new ConnDb(); 14 System.out.println(connDb.conn()); 15 } 16 }
SearchServlet.java:
1 package com.thanlon.servlet; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.thanlon.services.SearchNameServices; 13 14 import net.sf.json.JSONObject; 15 16 public class SearchServlet extends HttpServlet { 17 @Override 18 protected void doPost(HttpServletRequest request, 19 HttpServletResponse response) throws ServletException, IOException { 20 // TODO Auto-generated method stub 21 response.setContentType("text/html;charset=utf-8"); 22 // System.out.println("連接成功反饋");// 測試是否成功連接 23 StringBuffer json1 = new StringBuffer();// 字元流 24 String line = null; 25 BufferedReader reader = request.getReader();// 讀取流 26 while ((line = reader.readLine()) != null) { 27 json1.append(line);// 接受的是JSON格式 28 } 29 30 System.out.println(json1);//得到的是JSON格式 31 // System.out.println(json1.toString());//得到的是字元串,雖然控制台輸出一樣 32 // 把得到的字元串封裝為JSON,再獲取裡面的傳過來用戶名 33 JSONObject jsonObject = JSONObject.fromObject(json1.toString()); 34 String stu_number = jsonObject.getString("stu_number"); 35 System.out.println(stu_number); 36 37 // 連接本地資料庫(採用MySql資料庫 ) 38 String stuName = SearchNameServices.selectNameInfo(stu_number); 39 System.out.println(stuName); 40 41 PrintWriter out = response.getWriter(); 42 // out.write(stuName);//本直接返回查到的姓名,在Android客戶端顯示就行,這裡還是封裝成JSON格式發送吧 43 44 String stu_name_json = "{\"stu_name\":\""+stuName+"\"}";//組裝json格式的字元串來傳送 45 System.out.println(stu_name_json); 46 out.write(stu_name_json); 47 out.flush(); 48 out.close(); 49 } 50 51 @Override 52 protected void doGet(HttpServletRequest request, 53 HttpServletResponse response) throws ServletException, IOException { 54 // TODO Auto-generated method stub 55 // super.doGet(req, resp); 56 57 response.setContentType("text/html;charset=utf-8"); 58 PrintWriter out = response.getWriter(); 59 out.flush(); 60 out.close(); 61 } 62 }
SearchNameServices.java:
1 package com.thanlon.services; 2 3 import java.sql.PreparedStatement; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 7 import javax.naming.spi.DirStateFactory.Result; 8 import javax.validation.constraints.Null; 9 10 import com.thanlon.dao.ConnDb; 11 12 public class SearchNameServices { 13 14 public static String selectNameInfo(String stu_number){ 15 String stu_nameString = null; 16 String sql = "select *from student where stu_number = '"+stu_number+"'"; 17 ConnDb connDb = new ConnDb(); 18 try { 19 // 執行SQL語句 20 PreparedStatement ps = connDb.conn().prepareStatement(sql); 21 ResultSet rs = ps.executeQuery(); 22 if (rs.next()) { 23 stu_nameString =rs.getString("stu_name"); 24 return stu_nameString; 25 }else { 26 return stu_nameString="查無此人"; 27 } 28 } catch (SQLException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 System.out.println("執行SQL語句出錯!"); 32 } 33 return null; 34 } 35 }
附:個人網站www.nxl123.cn(後臺採用Python Flask框架搭建,2019年1月1日將升級完成並正式啟用。哎,本人是學生狗呢!網站做的不好希望大家多多提意見或建議吧!?別罵我,打我就好,嘿嘿!……以後SEO什麼的還得多向大家學習……)