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
list.xml
注意事项:在AndroidManifest.xml里要加上
如下图样式
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;
/**
/**
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
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 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 selectAll() {
// TODO Auto-generated method stub
Connection connection = DBUtil.getConnection();
String sql = "select * from jsbtable";
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
List 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服务器
原码下载地址:https://download.csdn.net/download/qq_40529129/10993224