struts2+json+android整合开发解析

首先我们来开发服务器端程序,此案例采用eclipse开发工具

首先create a Dynamic web project项目,在Dynamic Web Project界面中配置Target runtime 及 Dynamic web module version (此版本案例选择的为2.5),点击完成即可。

搭建struts2的开发环境,引入以下类库文件,

struts2-json-plugin-2.1.8.1.jar

json-lib-2.1.jar

commons-collections-3.2.jar

commons-beanutils-1.7.0.jar

commons-lang-2.3.jar

commons-logging-1.0.4.jar

ezmorph-1.0.3.jar

这7个包是返回json形式的数据必须的。因为json大量引用了Apache commons的包,所以要加入4个,commons包,除了commons的包外,还需要引入一个

ezmorph的包。最后加入struts2必须的6个包:

struts2-core-2.1.8.1.jar

xwork-core-2.1.6.jar

ognl-2.7.3.jar

freemarker-2.3.15.jar

commons-fileupload-1.2.1.jar

commons-io-1.3.2.jar

修改web.xml及添加struts.xml文件()

web.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

struts.xml位于src目录内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

</struts>

创建相应的实体bean,业务层及action层

package cn.redarmy.domain;

import java.io.Serializable;

public class Good implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String name;
    private float price;
//省去了.构造器 set,get方法

//service层

接口:

import java.util.List;

import cn.redarmy.domain.Good;

public interface GoodService {

    public abstract List<Good> getNewsGood();

    public abstract Good findGood();

}

类:

package cn.redarmy.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;

public class GoodServiceImpl implements GoodService {

    /* (non-Javadoc)
     * @see cn.redarmy.service.impl.GoodService#getNewsGood()
     */
    @Override
    public List<Good> getNewsGood() {
        // 定义返回的结果集
        List<Good> goods = new ArrayList<Good>();
        // 在这里可以到数据库中查询最新的商品信息
        goods.add(new Good(1, "苹果ipad2", 3688));
        goods.add(new Good(2, "thinkPad E40 0579A12", 3799));
        goods.add(new Good(3, "thinkPad", 3688));
        goods.add(new Good(4, "苹果ipad2保护膜", 400));
        return goods;
    }

    /* (non-Javadoc)
     * @see cn.redarmy.service.impl.GoodService#findGood()
     */
    @Override
    public Good findGood() {
        // 也是从数据库中查询出来的
        Good good = new Good(1, "苹果ipad2", 3688);
        return good;
    }
}

Action:

package cn.redarmy.action;

import java.util.List;

import cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;
import cn.redarmy.service.impl.GoodServiceImpl;

import com.opensymphony.xwork2.ActionSupport;

public class GoodAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 6340167538296898588L;

    // 定义业务操作bean
    private GoodService goodService = new GoodServiceImpl();

    // 定义返回的对象
    private List<Good> goods;
    private Good good;

    public List<Good> getGoods() {
        return goods;
    }

    public void setGoods(List<Good> goods) {
        this.goods = goods;
    }

    public Good getGood() {
        return good;
    }

    public void setGood(Good good) {
        this.good = good;
    }

    // 查询最新商品
    public String findAll() {
        goods = goodService.getNewsGood();
        return SUCCESS;
    }

    // 查询单个商品
    public String findById() {
        good = goodService.findGood();
        return SUCCESS;
    }

}

配置后的struts.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />

                                            <!-- extends 继承json-default -->
    <package name="default" namespace="/csdn" extends="json-default">
        <action name="findGood" class="cn.redarmy.action.GoodAction"
            method="findById">
            <!-- 设置返回类型为json -->
            <result name="success" type="json">
                <param name="includeProperties">
                    good\.id,good\.name,good\.price
                </param>
            </result>
            <result name="input">/WEB-INF/index.jsp</result>
        </action>
        <action name="listNewsGoods" class="cn.redarmy.action.GoodAction"
            method="findAll">
            <!-- 设置返回类型为json -->
            <result name="success" type="json">
                <param name="includeProperties">
                    goods\[\d+\]\.id,goods\[\d+\]\.name,goods\[\d+\]\.price
                </param>
            </result>
            <result name="input">/WEB-INF/index.jsp</result>
        </action>
    </package>

</struts>

至此服务器端开发已经完毕,在这里我比没有真正的从数据库提取数据,而是写死得,但如果连接数据库的操作那对于你来说应该不难吧!

上面我们重点介绍了struts2+json+android服务器段的开发,那接着我们就重点介绍在android客户端是怎么解析json集合|实体对象的方式

1、首先在这里我们新建一个android2.2的项目,新建完毕后因为此项目要进行网络访问操作,所以第一步应该在androidMainifest.xml文件中添加网络访问权限代码如下:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

2、然后创建业务bean及service对应的类代码如下:

业务Bean与上节课程中的业务一致。

Servcie层:

接口:

package cn.redarmy.service;

import java.util.List;

import cn.redarmy.domain.Good;

public interface GoodService {

    // 获取最新的商品信息
    public abstract List<Good> findAll();

    // 获取最新的单个商品的详细信息
    public abstract Good findById();

}

Service接口的实现类:在这里我们首先完成对商品的详细信息的解析:

package cn.redarmy.service.Impl;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;

public class GoodServiceImpl implements GoodService {

    // 获取最新的商品信息
    /* (non-Javadoc)
     * @see cn.redarmy.service.Impl.GoodService#findAll()
     */
    @Override
    public List<Good> findAll() {
        // 创建请求HttpClient客户端
        HttpClient httpClient = new DefaultHttpClient();
        // 创建请求的url
        String url = "http://192.168.4.32:8080/shop/csdn/listNewsGoods.action";
        try {
            // 创建请求的对象
            HttpGet get = new HttpGet(new URI(url));
            // 发送get请求
            HttpResponse httpResponse = httpClient.execute(get);
            // 如果服务成功返回响应
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    // 获取服务器响应的json字符串
                    String json = EntityUtils.toString(entity);
                    return parseArrayJosn(json);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //解析json数组对象
    private List<Good> parseArrayJosn(String json) {
        List<Good> goods = new ArrayList<Good>();
        try {
            JSONArray array = new JSONObject(json).getJSONArray("goods");
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                Good good = new Good(obj.getInt("id"), obj.getString("name"),
                        (float) obj.getDouble("price"));
                goods.add(good);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return goods;
    }

    // 获取最新的单个商品的详细信息
    /* (non-Javadoc)
     * @see cn.redarmy.service.Impl.GoodService#findById()
     */
    @Override
    public Good findById() {
        // 创建请求HttpClient客户端
        HttpClient httpClient = new DefaultHttpClient();
        // 创建请求的url
        String url = "http://192.168.4.32:8080/shop/csdn/findGood.action";
        try {
            // 创建请求的对象
            HttpGet get = new HttpGet(new URI(url));
            // 发送get请求
            HttpResponse httpResponse = httpClient.execute(get);
            // 如果服务成功返回响应
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    // 获取服务器响应的json字符串
                    String json = EntityUtils.toString(entity);
                    return parseObjJosn(json);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //解析json的单个对象
    private Good parseObjJosn(String json) {
        JSONObject obj = null;
        try {
            obj = new JSONObject(json).getJSONObject("good");
            Good good = new Good(obj.getInt("id"), obj.getString("name"),
                    (float) obj.getDouble("price"));
            return good;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

创建用于显示商品信息的listView及对应的组件

创建good.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="horizontal">
    <TextView android:layout_height="wrap_content" android:text="TextView" android:id="@+id/name" android:layout_width="200dip"></TextView>
    <TextView android:layout_height="wrap_content" android:text="TextView" android:id="@+id/price" android:layout_width="match_parent"></TextView>
    
</LinearLayout>

在main.xml文件中添加listView组件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/goods"></ListView>
</LinearLayout>

最后完成GoodActivity的编写代码如下:

package cn.redarmy.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;
import cn.redarmy.service.Impl.GoodServiceImpl;

public class GoodActivity extends Activity {
  
    private GoodService goodService = new GoodServiceImpl();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   //解析集合
   /*   try {
            List<Good> goods = goodService.findAll();
            ListView listView = (ListView) this.findViewById(R.id.goods);
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            for (Good good : goods) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("name", good.getName());
                item.put("price", getResources().getString(R.string.price)+good.getPrice());
                item.put("id", good.getId());
                data.add(item);
            }
            SimpleAdapter adapter = new SimpleAdapter(this, data,
                    R.layout.good, new String[] { "name", "price" },
                    new int[] { R.id.name, R.id.price });

            listView.setAdapter(adapter);
        } catch (Exception e) {
            Log.v("error", "网络连接失败");
            e.printStackTrace();
        }*/
     //解析单个对象
        try {
            Good good = goodService.findById();
            ListView listView = (ListView) this.findViewById(R.id.goods);
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
            
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("name", good.getName());
                item.put("price", getResources().getString(R.string.price)+good.getPrice());
                item.put("id", good.getId());
                data.add(item);
            
            SimpleAdapter adapter = new SimpleAdapter(this, data,
                    R.layout.good, new String[] { "name", "price" },
                    new int[] { R.id.name, R.id.price });

            listView.setAdapter(adapter);
        } catch (Exception e) {
            Log.v("error", "网络连接失败");
            e.printStackTrace();
        }
    }
}

通过以上方式就能实现struts2+android+json的开发了,希望你所有收获

留下评论

鄂ICP备13000209号-1

鄂公网安备 42050602000277号