Android+Servlet+MySql+JSON实现简单的数据查询操作

本例简单地实现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:

Package
 1 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什么的还得多向大家学习……)

 

Android+Servlet+MySql+JSON实现简单的数据查询操作

全文结束