jsp 产生json数据
--服务端代码
2.服务器端的service类
3.服务器端servlet类,接受android端的请求,并且将List中的Person数据转换为Json的格式,实现Json的数据传输
2.客户端主要类,MainActivity,发送请求
服务器端主要代码:
1.首先构建一个Person类,用来保存用户信息
- 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类
- 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的数据传输
- 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中加入引用包的代码
- <%@ page import="java.util.*"%>
- <%@ page import="java.sql.*"%>
结果测试:在浏览器输入localhost:8080/JsonWeb/JsonServlet,返回格式化好的json数据
--客户端代码
1.客户端文件,JsonParse,Json文件解析
- 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,发送请求
- 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构造的数据类
- 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别忘记添加
- <uses-permission android:name="android.permission.INTERNET" />
- <?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>