- 浏览: 23046 次
- 性别:
- 来自: 北京
最新评论
--服务端代码
服务器端主要代码:
1.首先构建一个Person类,用来保存用户信息
[java] view plaincopy
public class Person
private String name;
private String address;
private Integer age;
public Person() {
super();
}
public Person(String name, String address, Integer age) {
super();
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
2.服务器端的service类
[java] view plaincopy
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
public class JsonService {
public static List<Person> getListPerson(){
String a,b,allString = "";
int c = 0;
List<Person> mLists = new ArrayList<Person>();
// List<Person> mLists = new ArrayList<Person>();
// mLists.add(new Person("临风", "北京", 20));
System.out.println(mLists);
try {
Class.forName("com.mysql.jdbc.Driver");//链接数据库
Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/json", "root" , "123456");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from people");//遍历数据库
Person p = null;
while(rs.next())
{
System.out.println(rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getInt(3));
a = rs.getString(1);
b = rs.getString(2);
c = rs.getInt(3);
mLists.add(new Person(a, b, c));//添加到List中
}
System.out.println(mLists);
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
return mLists;
}
// finally{
// return mLists;
// }
System.out.println(mLists);
return mLists;
}
//测试用主函数
public static void main(String[] args) throws Exception
{
String str[] = null;
JsonService con = new JsonService();
List<Person> temp = con.getListPerson();
// System.out.println(temp.);
// str = temp.split(" ");
// for(int i = 0 ; i < str.length ; i++){
// System.out.println(str[i]);
// }
// System.out.println(str.length);
}
}
3.服务器端servlet类,接受android端的请求,并且将List中的Person数据转换为Json的格式,实现Json的数据传输
[java] view plaincopy
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jiangqq.bean.Person;
import com.jiangqq.csdn.JsonService;
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try{
PrintWriter out = response.getWriter();
List<Person> persons = JsonService.getListPerson();//返回JsonService的数据
StringBuffer sb = new StringBuffer();//数据缓存
sb.append('[');
for (Person person : persons) {//person.getName(),person.getAddress()获得姓名,地址,一些符号转换为char
//锁定输出=> {"name":"姓名","address":"地址","age":年龄},
sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(",");
sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
sb.append("\"age\":").append(person.getAge());
sb.append('}').append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(']');
out.write(new String(sb));
out.flush();
out.close();//关闭
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
环境搭建:
1.在Tomcat 7.0\webapps\JsonWeb\WEB-INF\lib 目录中加入了mysql-connector-java-5.0.8-bin.jar以及servlet-api.jar
2.然后在主目Tomcat 7.0\webapps\JsonWeb录的index.jsp中加入引用包的代码
[java] view plaincopy
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
结果测试:在浏览器输入http://localhost:8080/JsonWeb/JsonServlet,返回格式化好的json数据
--客户端代码
1.客户端文件,JsonParse,Json文件解析
[java] view plaincopy
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.jiangqq.bean.Person;
public class JsonParse {
/**
* 解析Json数据
*
* @param urlPath
* @return mlists
* @throws Exception
*/
public static List<Person> getListPerson(String urlPath) throws Exception {
List<Person> mlists = new ArrayList<Person>();
byte[] data = readParse(urlPath);
JSONArray array = new JSONArray(new String(data));
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String name = item.getString("name");
String address = item.getString("address");
int age = item.getInt("age");
mlists.add(new Person(name, address, age));
}
return mlists;
}
/**
* 从指定的url中获取字节数组
*
* @param urlPath
* @return 字节数组
* @throws Exception
*/
public static byte[] readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
2.客户端主要类,MainActivity,发送请求
[java] view plaincopy
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.jiangqq.bean.Person;
import com.jiangqq.util.JsonParse;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mButton;
private ListView mListView;
private static final String urlPath = "http://192.168.1.100:8080/JsonWeb/JsonServlet";
private static final String TAG = "MainActivity";
private List<Person> persons;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.button1);
mListView = (ListView) findViewById(R.id.listView1);
mButton.setOnClickListener(new MyOnClickListener());
}
private class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
// 得到Json解析成功之后数据
persons = JsonParse.getListPerson(urlPath);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < persons.size(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", persons.get(i).getName());
map.put("address", persons.get(i).getAddress());
map.put("age", persons.get(i).getAge());
data.add(map);
}
SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
data, R.layout.listview_item, new String[] { "name",
"address", "age" }, new int[] { R.id.textView1,
R.id.textView2, R.id.textView3 });
mListView.setAdapter(_Adapter);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "解析失败", 2000);//在手机上显示提示Toast,2秒
Log.i(TAG, e.toString());//DDMS中显示提示
}
}
}
}
3.同上一篇的,Person构造的数据类
[java] view plaincopy
package com.jiangqq.bean;
public class Person {
private String name;
private String address;
private Integer age;
public Person() {
super();
}
public Person(String name, String address, Integer age) {
super();
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age
+ "]";
}
}
4.AndroidManifest.xml别忘记添加
[java] view plaincopy
<uses-permission android:name="android.permission.INTERNET" />
[java] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jiangqq.csdn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
服务器端主要代码:
1.首先构建一个Person类,用来保存用户信息
[java] view plaincopy
public class Person
private String name;
private String address;
private Integer age;
public Person() {
super();
}
public Person(String name, String address, Integer age) {
super();
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
2.服务器端的service类
[java] view plaincopy
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
public class JsonService {
public static List<Person> getListPerson(){
String a,b,allString = "";
int c = 0;
List<Person> mLists = new ArrayList<Person>();
// List<Person> mLists = new ArrayList<Person>();
// mLists.add(new Person("临风", "北京", 20));
System.out.println(mLists);
try {
Class.forName("com.mysql.jdbc.Driver");//链接数据库
Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/json", "root" , "123456");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from people");//遍历数据库
Person p = null;
while(rs.next())
{
System.out.println(rs.getString(1) + "\t"
+ rs.getString(2) + "\t"
+ rs.getInt(3));
a = rs.getString(1);
b = rs.getString(2);
c = rs.getInt(3);
mLists.add(new Person(a, b, c));//添加到List中
}
System.out.println(mLists);
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
return mLists;
}
// finally{
// return mLists;
// }
System.out.println(mLists);
return mLists;
}
//测试用主函数
public static void main(String[] args) throws Exception
{
String str[] = null;
JsonService con = new JsonService();
List<Person> temp = con.getListPerson();
// System.out.println(temp.);
// str = temp.split(" ");
// for(int i = 0 ; i < str.length ; i++){
// System.out.println(str[i]);
// }
// System.out.println(str.length);
}
}
3.服务器端servlet类,接受android端的请求,并且将List中的Person数据转换为Json的格式,实现Json的数据传输
[java] view plaincopy
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jiangqq.bean.Person;
import com.jiangqq.csdn.JsonService;
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try{
PrintWriter out = response.getWriter();
List<Person> persons = JsonService.getListPerson();//返回JsonService的数据
StringBuffer sb = new StringBuffer();//数据缓存
sb.append('[');
for (Person person : persons) {//person.getName(),person.getAddress()获得姓名,地址,一些符号转换为char
//锁定输出=> {"name":"姓名","address":"地址","age":年龄},
sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(",");
sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
sb.append("\"age\":").append(person.getAge());
sb.append('}').append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(']');
out.write(new String(sb));
out.flush();
out.close();//关闭
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
环境搭建:
1.在Tomcat 7.0\webapps\JsonWeb\WEB-INF\lib 目录中加入了mysql-connector-java-5.0.8-bin.jar以及servlet-api.jar
2.然后在主目Tomcat 7.0\webapps\JsonWeb录的index.jsp中加入引用包的代码
[java] view plaincopy
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
结果测试:在浏览器输入http://localhost:8080/JsonWeb/JsonServlet,返回格式化好的json数据
--客户端代码
1.客户端文件,JsonParse,Json文件解析
[java] view plaincopy
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.jiangqq.bean.Person;
public class JsonParse {
/**
* 解析Json数据
*
* @param urlPath
* @return mlists
* @throws Exception
*/
public static List<Person> getListPerson(String urlPath) throws Exception {
List<Person> mlists = new ArrayList<Person>();
byte[] data = readParse(urlPath);
JSONArray array = new JSONArray(new String(data));
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String name = item.getString("name");
String address = item.getString("address");
int age = item.getInt("age");
mlists.add(new Person(name, address, age));
}
return mlists;
}
/**
* 从指定的url中获取字节数组
*
* @param urlPath
* @return 字节数组
* @throws Exception
*/
public static byte[] readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
2.客户端主要类,MainActivity,发送请求
[java] view plaincopy
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.jiangqq.bean.Person;
import com.jiangqq.util.JsonParse;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mButton;
private ListView mListView;
private static final String urlPath = "http://192.168.1.100:8080/JsonWeb/JsonServlet";
private static final String TAG = "MainActivity";
private List<Person> persons;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.button1);
mListView = (ListView) findViewById(R.id.listView1);
mButton.setOnClickListener(new MyOnClickListener());
}
private class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
// 得到Json解析成功之后数据
persons = JsonParse.getListPerson(urlPath);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < persons.size(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", persons.get(i).getName());
map.put("address", persons.get(i).getAddress());
map.put("age", persons.get(i).getAge());
data.add(map);
}
SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
data, R.layout.listview_item, new String[] { "name",
"address", "age" }, new int[] { R.id.textView1,
R.id.textView2, R.id.textView3 });
mListView.setAdapter(_Adapter);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "解析失败", 2000);//在手机上显示提示Toast,2秒
Log.i(TAG, e.toString());//DDMS中显示提示
}
}
}
}
3.同上一篇的,Person构造的数据类
[java] view plaincopy
package com.jiangqq.bean;
public class Person {
private String name;
private String address;
private Integer age;
public Person() {
super();
}
public Person(String name, String address, Integer age) {
super();
this.name = name;
this.address = address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age
+ "]";
}
}
4.AndroidManifest.xml别忘记添加
[java] view plaincopy
<uses-permission android:name="android.permission.INTERNET" />
[java] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jiangqq.csdn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
发表评论
-
android xml界面布局常用属性概括
2014-01-23 19:54 1851布局: 在 android 中我们常用的布局方式有这么 ... -
HttpClient4.0
2014-01-18 10:20 530HttpClient程序包是一个实现了 HTTP 协议的客户端 ... -
afinal logoAndroid的快速开发框架 afinal
2014-01-13 08:49 1407Afinal简介 Afinal 是一个android的sqli ... -
Android使用Fragment嵌套Fragment的方式实现界面滑动
2014-01-11 14:23 2345// 主Activity public class HomeA ... -
Google的GSON框架解析JSON数据
2014-01-08 09:18 1077什么是JSON: JSON即JavaScript Object ... -
关于安卓应用账号退出
2014-01-04 16:21 403首先,我们将管理Activity的功能通过一个扩展的Appli ... -
安卓学习的起源
2013-12-28 12:03 457首先我先自我简单介绍下,我是一名计算机系本科专业的毕业生,目前 ...
相关推荐
本文将深入解析一个基于Android客户端、Tomcat服务器、MySQL数据库以及JSP技术的无线点餐系统。这个系统通过一万行代码实现了从用户点餐到后台管理的全套流程,非常适合学习和实践。 首先,Android作为点餐系统...
6. **部署与运行**:将项目打包成WAR文件,部署到支持JSP和Servlet的Web服务器(如Tomcat),通过浏览器访问指定URL,即可看到从MySQL数据库中获取并显示的内容。 本项目中的"aaa"可能是实际的源代码文件,包含了...
本教程将探讨如何在Android客户端实现一个登录系统,该系统能够与基于JSP、Servlet和MySQL的后端服务器协同工作。首先,我们需要理解Android客户端与服务器交互的基本原理,然后详细介绍每个组成部分的作用。 **...
这里用安卓连接Tomcat用JSP做服务器, 有如下功能:用户登录、图片上传、数据传输(JSON) 里面包含了xUtils用于安卓端图片上传 json-taglib-0.4.1 commons-dbutils-1.7jar jspsmartupload
这个“android通过连接服务器验证实现登录的demo”就是一个很好的实例,展示了如何利用Android客户端、JSP、Servlet、Tomcat服务器以及MySQL数据库协同工作,完成用户的登录验证。 首先,我们来看Android客户端部分...
总之,通过Android Studio开发的应用利用Servlet作为与PC端MySQL数据库的接口,可以实现数据的读取和写入。这个过程涉及Android的网络请求、Servlet的编程以及JDBC与MySQL的交互。理解并掌握这些技术对于构建基于...
基于Android开发的APP服务器...本文系统地介绍了基于Android平台的APP服务器端设计,讨论了服务器端的需求分析和设计、服务器交互原理和实现方法、Java编程语言、MYSQL数据库、Apache Tomcat和Struts2框架等关键技术。
在本教程中,我们将深入探讨如何使用Tomcat作为应用服务器和MySQL作为数据库,为您的Android APP构建后端服务器。在“Tomcat+MySQL为自己的APP打造服务器(4)完结篇Demo”中,我们重点关注的是实际的示例代码,涵盖...
在这个“Ajax Jsp 连接MySQL数据库”的主题中,我们将深入探讨如何在JSP页面上利用Ajax技术与后台MySQL数据库进行交互,同时处理多个Ajax请求。 首先,让我们了解基本概念。Ajax的核心是通过JavaScript向服务器发送...
【安卓 一个简单新闻系统...总的来说,这个项目涵盖了从服务器端开发到客户端应用的全过程,涉及Web服务、数据库操作、网络通信、数据解析等多个方面,对于学习和理解安卓应用开发以及后端服务构建具有很好的实践意义。
- **服务器端编程**:可能使用Java的Servlet和JSP技术,处理客户端请求,与数据库交互,生成响应数据。 4. **数据库管理**: - **MySQL**:是一种关系型数据库管理系统,广泛应用于Web应用中。在这个选课系统中,...
在Android与JSP的数据交互中,JSON常被用作数据传输的载体,因为它的结构清晰,支持复杂的数据结构,且跨平台兼容性好。 JSP(JavaServer Pages)是基于Java的动态网页技术,它允许开发者在HTML页面中嵌入Java代码...
web项目jsp后台_servlet入门练习demo+可返回json+说明文档+数据库。 === 可以用来做android服务端测试,也可以作为java开发入门练习。 === demo_myweb:项目目录 lxb_test.sql:数据库文件 ====== 数据库版本 mysql...
在Android平台上开发一个酒店房间预订系统,涉及到的技术栈主要包括Android应用开发、MySQL数据库管理和Tomcat服务器部署。这个项目的核心目标是实现用户通过Android设备预订酒店房间的功能,为用户提供便捷的预订...
其中Myecplise作为开发工具,采用Mysql作为数据库服务器,Tomcat作为网络服务器。 (1)权限管理:对权限信息进行添加、删除、修改和查看 (2)用户管理:对用户信息进行添加、删除、修改和查看 (3)项目管理:对项目...