转自:http://www.cnblogs.com/android-html5/archive/2011/09/25/2534107.html
android--使用Struts2服务端与android交互
一,服务器端:
首先搭建struts2的环境,导入必要的类库。
web.xml文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
struts.xml文件:
- <?xml version="1.0" encoding="GBK"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="testjson" <span style="color:#ff0000;">extends="json-default"</span>>
- <action name="getjson" class="com.shao.action.JSONAction" method="json">
- <result type="json"></result>
- </action>
- </package>
- </struts>
Action类:
- package com.shao.action;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import com.google.gson.Gson;
- import com.opensymphony.xwork2.ActionSupport;
- import com.shao.domain.Music;
- public class JSONAction extends ActionSupport implements ServletRequestAware,
- ServletResponseAware {
- /**
- *
- */
- private static final long serialVersionUID = -3604892179657815531L;
- private HttpServletRequest request;
- private HttpServletResponse response;
- private String format;
- public String getFormat() {
- return format;
- }
- public void setFormat(String format) {
- this.format = format;
- }
- @Override
- public void setServletRequest(HttpServletRequest request) {
- // TODO Auto-generated method stub
- this.request = request;
- }
- @Override
- public void setServletResponse(HttpServletResponse response) {
- // TODO Auto-generated method stub
- this.response = response;
- }
- public void json(){
- List<Music> list = new ArrayList<Music>();
- // JsonArray jsonArray = new JsonArray();
- // JsonObject jsonObject = new JsonObject();
- Gson gson = new Gson();
- Music m1 = new Music();
- m1.setId(1);
- m1.setAuthor("游鸿明");
- m1.setName("白色恋人");
- m1.setTime("04:01");
- list.add(m1);
- Music m2 = new Music();
- m2.setId(2);
- m2.setAuthor("陈奕迅");
- m2.setName("淘汰");
- m2.setTime("04:44");
- list.add(m2);
- Music m3 = new Music();
- m3.setId(3);
- m3.setAuthor("谢霆锋");
- m3.setName("黄种人");
- m3.setTime("04:24");
- list.add(m3);
- java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
- }.getType();
- String beanListToJson = gson.toJson(list,type);
- System.out.println("GSON-->"+beanListToJson);
- try {
- response.setCharacterEncoding("GBK");
- //response.setContentType("text/xml;charset=utf-8");
- this.response.getWriter().write(beanListToJson);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- package com.shao.domain;
- public class Music {
- private Integer id;
- private String name;
- private String time;
- private String author;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getTime() {
- return time;
- }
- public void setTime(String time) {
- this.time = time;
- }
- public String getAuthor() {
- return author;
- }
- public void setAuthor(String author) {
- this.author = author;
- }
- }
访问 http://localhost:8080/Client/getjson.action;结果:
二,android客户端:
Activity类:
- package com.shao.main;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- public class JsonClientActivity extends Activity {
- /** Called when the activity is first created. */
- private Button update;
- private ListView listView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- update = (Button) findViewById(R.id.update);
- listView = (ListView) findViewById(R.id.list);
- update.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- String urlStr="http://10.0.2.2:8080/Client/getjson.action";
- String result = GsonUtil.getJson(urlStr);
- List<Music> list = GsonUtil.getListFromJson(result);
- List<Map<String,Object>> data = getAdapterData(list);
- SimpleAdapter adapter =new SimpleAdapter(JsonClientActivity.this, data, R.layout.list, new String[]{"name","author","time"}, new int[]{R.id.name,R.id.author,R.id.time});
- listView.setAdapter(adapter);
- //listView.
- }
- });
- }
- private List<Map<String,Object>> getAdapterData(List list){
- List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
- for(int i=0;i<list.size();i++){
- Map<String,Object> map = new HashMap<String, Object>();
- Music music= (Music)list.get(i);
- map.put("name",music.getName());
- map.put("author", music.getAuthor());
- map.put("time",music.getTime());
- data.add(map);
- }
- return data;
- }
- }
- package com.shao.main;
- import java.net.URI;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import com.google.gson.Gson;
- public class GsonUtil {
- public static String getJson(String url){
- HttpClient client = new DefaultHttpClient();
- HttpPost request;
- try {
- request = new HttpPost(new URI(url));
- HttpResponse response = client.execute(request);
- // 判断请求是否成功
- if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功
- HttpEntity entity = response.getEntity();
- if(entity!=null){
- String beanListToJson = EntityUtils.toString(entity,"GBK");
- return beanListToJson;
- }
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- return null;
- }
- public static List<Music> getListFromJson(String json){
- java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
- }.getType();
- Gson gson = new Gson();
- List<Music> list = gson.fromJson(json, type);
- return list;
- }
- }
list.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="name"
- />
- <TextView
- android:id="@+id/author"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/name"
- android:paddingTop="5px"
- android:text="author"
- >
- </TextView>
- <TextView
- android:id="@+id/time"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/name"
- android:layout_alignTop="@id/author"
- android:layout_alignParentRight="true"
- android:text="time">
- </TextView>
- </RelativeLayout>
主要的交互都是通过goolge的Gson完成