大体描述:
大体意思是用eclipse ee创建一个Javaweb项目,该项目能从MySQL数据库中获取user表的数据,将数据封装成json格式,将此项目发布到本地Tomcat服务器,在android端获取刚才的json数据,并用listview显示。废话不多说下面直接开始。
Tomcat服务器端
很简单,建立一个servlet用来处理数据,再建一个数据库工具类,我这里是DatabaseUtil.java,不要忘记servlet在web.xml中需要注册。
项目结构:
code:
ServletDemo1.java
package com.servlet.demo;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
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 net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.DatabaseUtil;
public class ServletDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDemo1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sql = "select * from user";
JSONArray jsonArray=new JSONArray(); //json数组
try {
ResultSet result = DatabaseUtil.query(sql);
while (result.next()) {
JSONObject jObject=new JSONObject(); //json临时对象
jObject.put("id", result.getInt(1));
jObject.put("username", result.getString(2));
jObject.put("password", result.getString(3));
jsonArray.add(jObject); //将封装好的json对象放入json数组
}
} catch (SQLException e) {
e.printStackTrace();
}
String jsondata=jsonArray.toString(); //将json数组转换成字符串,供下面返回给android端使用
//System.out.println(jsondata); //本地测试用
response.getWriter().append(jsondata).flush();
}
}
DatabaseUtil.java
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
public class DatabaseUtil {
private static Connection mConnection;
private static Connection getConnection() {
if (mConnection == null) {
String url = "jdbc:mysql://localhost:3306/mybatis";
try {
Class.forName("com.mysql.jdbc.Driver");
mConnection = (Connection) DriverManager.getConnection(url, "root", "123");
} catch (Exception e) {
e.printStackTrace();
}
}
return mConnection;
}
//这里只用了查询操作
public static ResultSet query(String querySql) throws SQLException {
Statement stateMent = (Statement) getConnection().createStatement();
return stateMent.executeQuery(querySql);
}
public static void closeConnection() {
if (mConnection != null) {
try {
mConnection.close();
mConnection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ConnectTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.servlet.demo.ServletDemo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/ServletDemo1</url-pattern>
</servlet-mapping>
</web-app>
本地测试结果
在浏览器地址栏里输入(端口啥的自己改了的话用自己的,不多说)
http://localhost:8080/ConnectTest/ServletDemo1
测试结果:
android端
也比较简单,有两个activity,在mainactivity中有个button按钮,点击后跳转到第二个activity,我这里是ListActivity ,在listactivity中显示获取到的json数据。
用到的jar包
类
布局
code
工具类 HttpUtil
package util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
}
实体类 User
package com.ccc.connecttest.activity;
public class User {
private int id;
private String username;
private String password;
public User(int id,String username, String password){
this.id=id;
this.username=username;
this.password=password;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
适配器 UserAdapter
package com.ccc.connecttest.activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ccc.connecttest.R;
import java.util.List;
public class UserAdapter extends ArrayAdapter<User> {
private int resourceId;
public UserAdapter(Context context, int resourceId, List<User> objects) {
super(context, resourceId,objects);
this.resourceId=resourceId;
}
@Override
public View getView(int position, View convertView,ViewGroup parent) {
User user=getItem(position);
View view;
ViewHolder viewHolder;
if(convertView==null){
view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
viewHolder=new ViewHolder();
viewHolder.userid=(TextView)view.findViewById(R.id.tv_id);
viewHolder.username=(TextView)view.findViewById(R.id.tv_username);
viewHolder.userpassword=(TextView)view.findViewById(R.id.tv_password);
view.setTag(viewHolder); //将viewHolder存储在view中
}else{
view=convertView;
viewHolder=(ViewHolder)view.getTag();
}
viewHolder.userid.setText(String.valueOf(user.getId()));
viewHolder.username.setText(user.getUsername());
viewHolder.userpassword.setText(user.getPassword());
return view;
}
static class ViewHolder{
TextView userid;
TextView username;
TextView userpassword;
}
}
显示的页面 ListActivity
package com.ccc.connecttest.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import com.ccc.connecttest.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import util.HttpUtil;
public class ListActivity extends AppCompatActivity {
private List<User> userList=new ArrayList<>();
private ListView listView;
private String json_url="http://192.168.2.133:8080/ConnectTest/ServletDemo1";//本地Tomcat刚才测试的地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
queryFromServer(json_url); //处理取得数据
listView=findViewById(R.id.lv);
UserAdapter adapter = new UserAdapter(ListActivity.this, R.layout.user, userList);
listView.setAdapter(adapter);
}
private void queryFromServer(String json_url) {
HttpUtil.sendOkHttpRequest(json_url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("error","出现错误!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText=response.body().string();
try {
JSONArray jsonArray=new JSONArray(responseText);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String id=jsonObject.getString("id");
String username=jsonObject.getString("username");
String password=jsonObject.getString("password");
User user=new User(Integer.parseInt(id),username,password);
userList.add(user);
Log.i("user","添加了一个User");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
主页面 MainActivity
package com.ccc.connecttest.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.ccc.connecttest.R;
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.btnSign);
//点击跳转到显示页面
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ListActivity.class));
}
});
}
}
配置 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ccc.connecttest">
<!-- 千万不要忘了申请使用网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 这个ListActivity不要忘记注册-->
<activity android:name=".activity.ListActivity"/>
</application>
</manifest>
布局
activity_main.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:orientation="vertical" >
<Button
android:layout_marginTop="200dp"
android:id="@+id/btnSign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="获取" />
</LinearLayout
activity_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
listview每一项适配文件: user.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_id"
android:text="1111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<TextView
android:text="2222"
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
<TextView
android:text="3333"
android:id="@+id/tv_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#d97e87"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
结果图
附上源码
新demo 用retrofit实现的 上面那个很久以前做的没注意 有问题
new demo
https://github.com/Commandercc/smallthings/blob/master/GetJsonDemo.zip 这个新的demo可以看一下