Android前端通过Http协议与J2EE后端数据交互。工具eclipse、MySQL、Tomcat。通过JoSn获取数据。Android端实现对MySQL增删改查功能。

Android:目录
在项目这里插入图片描述

HttpThread.java
package com.example.saads;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.string;

public class HttpThread extends Thread {
String url;
String title;
String content;

public HttpThread(String url, String title, String content) {
    // TODO Auto-generated constructor stub
    this.url = url;
    this.title = title;
    this.content = content;
}

private void doGet() throws IOException {
    /*将title和content传给Tomcat服务器*/
    url=url+"?title="+title+"&content="+content;
    try {
        URL httpUrl = new URL(url);
        /*获取网络连接*/
        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
        /*设置请求方法为GET方法*/
        conn.setRequestMethod("GET");
        /*设置访问超时时间*/
        conn.setReadTimeout(5000);
        BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str;
        StringBuffer sb=new StringBuffer();
        //读取服务器返回的信息
        while((str=reader.readLine())!=null)
        {
            sb.append(str);
        }
        //把服务端返回的数据打印出来
        System.out.println("result"+sb.toString());
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

/*在run中调用doGet*/
@Override
public void run() {
    try {
        doGet();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

ListActivity.java //记得ip地址改为自己电脑的IP地址
package com.example.saads;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

class User {
private int id;
private String title;
private String content;

public int getId() {
	return id;
}

public void setId(int id) {
	this.id = id;
}

public String gettitle() {
	return title;
}

public void settitle(String title) {
	this.title = title;
}

public String getcontent() {
	return content;
}

public void setcontent(String content) {
	this.content = content;
}

@Override
public String toString() {
	return id + "、 标题:" + title +'\n'+"内容:" + content;

}

}
public class ListActivity extends Activity {
ListView listView;
List list = new ArrayList();
Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
listView.setAdapter(new ArrayAdapter(
ListActivity.this, android.R.layout.simple_expandable_list_item_1, list));
break;

		default:
			break;
		}
	};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_list);
	listView = (ListView) findViewById(R.id.list_view);
}

public void click(View view) {
	new Thread() {
		public void run() {
			Log.e("hua", "enter run");
			try {
				URL url = new URL(
						"http://192.168.1.108:8080/register/register"); 
				Log.e("hua", "url is " + url.toString());
				HttpURLConnection httpURLConnection = (HttpURLConnection) url
						.openConnection();
				//httpURLConnection.connect();
				int code = httpURLConnection.getResponseCode();
				if (code == 200) {
					InputStream is = httpURLConnection.getInputStream();
					StringBuffer stringBuffer = new StringBuffer();
					byte[] buffer = new byte[1024];
					while (is.read(buffer) != -1) {

						stringBuffer.append(new String(buffer));
					}
					JSONObject object = new JSONObject(
							stringBuffer.toString());
					JSONArray array = object.getJSONArray("list");
					for (int i = 0; i < array.length(); i++) {
						JSONObject jb = array.getJSONObject(i);
						int id = jb.getInt("id");
						String title = jb.getString("title");
						String content = jb.getString("content");
						User user = new User();
						user.setId(id);
						user.settitle(title);
						user.setcontent(content);
						Log.e("hua", user.toString());
						list.add(user.toString());
					}
					
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		};
	}.start();
}

}

MainActivity.java 下面的网络地址改为自己的IP地址。
package com.example.saads;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
private TextView title;
private TextView content;
private Button signup;
private Button butlishi;

@Override

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    title=(TextView) findViewById(R.id.etSgAccount);
    content=(TextView) findViewById(R.id.etSgPassword);
    signup=(Button) findViewById(R.id.baocun);
    butlishi=(Button) findViewById(R.id.lishi);
    butlishi.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MainActivity.this,ListActivity.class);
			
			startActivity(intent);
		}
	});

    
}


/*发起HTTP请求*/
public void onLogin(View v)
{
    String url="http://192.168.1.108:8080/register/MyServlet";
    
    new HttpThread(url, title.getText().toString(), content.getText().toString()).start();
}


@Override
public void onClick(View arg0) {
	// TODO Auto-generated method stub
	
}

}

界面很简单随便写了两个增加与查询的界面,写的很难看读者自行创作

max.xml

<?xml version="1.0" encoding="utf-8"?>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:textColor="#0F00C6"
        android:textSize="15sp"
        android:gravity="center"
        android:text="@string/edit_title_text"
        />

</LinearLayout>

<RelativeLayout
    android:id="@+id/body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="10dp"
    >

    <LinearLayout
        android:id="@+id/edit_title_lay_lay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        

        <LinearLayout
            android:id="@+id/edit_title_lay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/text_tile"
                android:textSize="15sp"
                />
            <EditText
                android:id="@+id/etSgAccount"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="15sp"
                android:hint="@string/edit_hint"

                />
        </LinearLayout>

    </LinearLayout>



  

    <Button
        android:id="@+id/lishi"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:text="@string/baocun"
        android:textColor="#0F00C6"
        android:textSize="20sp"

        />
    
    
    <EditText
        android:id="@+id/etSgPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/lishi"
        android:layout_below="@id/edit_title_lay_lay"
        android:layout_marginTop="10dp"
        android:gravity="start"
        android:hint="@string/Password"
        android:textSize="10sp" />

    <Button
        android:id="@+id/baocun"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="@string/lishi"
        android:textColor="#0F00C6"
        android:textSize="20sp"
        android:onClick="onLogin"
       
        />


</RelativeLayout>

list.xml

<RelativeLayout
    android:id="@+id/body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="10dp"
    >
    <Button
        android:id="@+id/createButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"            
        android:textSize="20sp"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true"
       android:onClick="click"
    android:text="查看记录"/>
        
    <ListView
        android:id="@+id/list_view"
        android:layout_above="@id/createButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="1dp"
        
        >
    </ListView>
</RelativeLayout>

注意事项:在AndroidManifest.xml里要加上

如下图样式

在这里插入图片描述

J2EE端
项目目录:
在这里插入图片描述

MyServlet extends.java
package com.ioss;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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 javax.sql.DataSource;

import org.apache.catalina.Context;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

/**

  • Servlet implementation class MyServlet
    */
    @WebServlet("/MyServlet")
    public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**

    • @see HttpServlet#HttpServlet()
      */
      public MyServlet() {
      super();
      // TODO Auto-generated constructor stub
      }

    /**

    • @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    •  response)
      

    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    this.doPost(request, response);
    }

    /**

    • @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    •  response)
      

    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

     String title = request.getParameter("title");
     String content = request.getParameter("content");
     PrintWriter out = response.getWriter();
     System.out.println("title" + ":" + title);
     System.out.println("content" + ":" + content);
    
     int rs ;
     String sql = "insert into jsbtable(id,title,content) values(null,?,?)";
    
    
     try {
         InitialContext ctx = new InitialContext();
         DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/jsb");
      
         java.sql.Connection conn =ds.getConnection();
         conn = ds.getConnection();
      
         PreparedStatement ps = conn.prepareStatement(sql);
         ps.setString(1, title);
         ps.setString(2, content);
         rs= ps.executeUpdate();
     } catch (SQLException se) {
         System.out.println("SQLException: " + se.getMessage());
     } catch (NamingException ne) {
         System.out.println("NamingException: " + ne.getMessage());
     }
    

    }
    }

DBUtil.java
package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
static String driver = “com.mysql.jdbc.Driver”;
static String url = “jdbc:mysql://localhost:3306/jsb”;
static String user = “root”;
static String password = “lmj1314”;
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url,user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

public static void close(PreparedStatement preparedStatement,
		Connection connection) {
	if (preparedStatement != null) {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if (connection != null) {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
public static void close(PreparedStatement preparedStatement,
		Connection connection,ResultSet resultSet) {
	if (preparedStatement != null) {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if (connection != null) {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if (resultSet != null) {
		try {
			resultSet.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

}

InsertUser.java
package com.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class InsertUser implements Dao {
Connection conn = DBUtil.getConnection();
PreparedStatement preparedStatement;
@Override
public void insertUser(User user) {
String title = user.gettitle();
String content = user.getcontent();
String sql = “insert into jsbtable(title,content) values(’” + title + “’,’” +content + “’)”;
System.out.println(sql);
try {
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBUtil.close(preparedStatement, conn);

}

@Override
public List<User> selectAll() {
	// TODO Auto-generated method stub
	return null;
}

}

SelectAll.java
package com.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SelectAll implements Dao {

@Override
public void insertUser(User user) {
	// TODO Auto-generated method stub
}

@Override
public List<User> selectAll() {
	// TODO Auto-generated method stub
	Connection connection = DBUtil.getConnection();
	String sql = "select * from jsbtable";
	ResultSet resultSet = null;
	PreparedStatement preparedStatement = null;
	List<User> list = new ArrayList<>();
	try {
		preparedStatement = connection.prepareStatement(sql);
		resultSet = preparedStatement.executeQuery();
		while (resultSet.next()) {
			User myuser = new User();
			myuser.setId(resultSet.getInt(1));
			myuser.settitle(resultSet.getString(2));
			myuser.setcontent(resultSet.getString(3));
			list.add(myuser);
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	DBUtil.close(preparedStatement, connection, resultSet);
	return list;
}

}

User
package com.jdbc;

import java.util.Date;

public class User {
private int id;
private String title;
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getcontent() {
return content;
}
public void setcontent(String content) {
this.content = content;
}
@Override
public String toString() {
return “User [id=” + id + “, title=” + title + “, content=” + content
+ “]”;
}

}

Register .java
package com.register;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;

import net.sf.json.JSONObject;

//import com.jdbc.InsertUser;
import com.jdbc.SelectAll;
import com.jdbc.User;

public class Register extends HttpServlet {
List list;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
SelectAll selectAll = new SelectAll();
list = selectAll.selectAll();

	JSONObject jsonObject=new JSONObject();

	//jsonObject.put(key, value);
	jsonObject.put("list", list);

	resp.setCharacterEncoding("utf-8");

	PrintWriter printWriter = resp.getWriter();
	printWriter.write(jsonObject.toString());
	// TODO Auto-generated method stub
	/*PrintWriter pWriter = resp.getWriter();
	pWriter.write(resp.getCharacterEncoding());
	String username = req.getParameter("username");
	String password = req.getParameter("password");
	System.out.println("------" + username + "," + password  + "--------");
	if (username == null || password == null || username.equals("")
		|| password.equals("")) {
		return;
	}
	username = new String(username.getBytes("iso-8859-1"),"utf-8");
	password = new String(password.getBytes("iso-8859-1"),"utf-8");
	username = URLDecoder.decode(username, "utf-8");
	password = URLDecoder.decode(password, "utf-8");
	System.out.println("------" + username + "," + password  + "--------");
	User user = new User();
	user.setName(username);
	user.setPassword(password);
	InsertUser insertUser = new InsertUser();
	insertUser.insertUser(user);*/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	/*PrintWriter pWriter = resp.getWriter();
	pWriter.write("hello");*/
	doGet(req, resp);
}

}

**配置Tomcat数据库连接池:
index.html
index.htm
index.jsp


DataServiceServlet
com.ioss.MyServlet


DataServiceServlet
/DataServiceServlet


DB Connection
jdbc/jsb
javax.sql.DataSource
Container

**

在这里插入图片描述

**打开Tomcat的context.xml加上如下图

我的MYSQL数据库中数据库名为JSB
表名为jsbtable
数据库密码为lmj1314
读者根据自己的数据库更改
**
在这里插入图片描述

MYSQL数据库设计

在这里插入图片描述

好了一切完毕!与老学长一起看看运行效果吧!
1、先看看MYSQL数据库里有什么吧!下图是初始的数据库数据
在这里插入图片描述

2、启动J2EE的Tomcat服务器

3、运行Android 输入数据并保存
在这里插入图片描述

J2 EE的效果:在这里插入图片描述

再看看数据库是不是保存进去了呢
在这里插入图片描述

Android端查看历史记录
在这里插入图片描述

看看J2EE端从数据库获取到的数据
在这里插入图片描述

原码下载地址:https://download.csdn.net/download/qq_40529129/10993224

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值