使用Struts2服务端与android交互

时间:2023-03-09 18:36:37
使用Struts2服务端与android交互

转自:http://www.cnblogs.com/android-html5/archive/2011/09/25/2534107.html

android--使用Struts2服务端与android交互

一,服务器端:

首先搭建struts2的环境,导入必要的类库。

使用Struts2服务端与android交互

web.xml文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <welcome-file-list>
  8. <welcome-file>index.jsp</welcome-file>
  9. </welcome-file-list>
  10. <filter>
  11. <filter-name>struts2</filter-name>
  12. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  13. </filter>
  14. <filter-mapping>
  15. <filter-name>struts2</filter-name>
  16. <url-pattern>/*</url-pattern>
  17. </filter-mapping>
  18. </web-app>

struts.xml文件:

  1. <?xml version="1.0" encoding="GBK"?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <package name="testjson" <span style="color:#ff0000;">extends="json-default"</span>>
  7. <action name="getjson" class="com.shao.action.JSONAction" method="json">
  8. <result type="json"></result>
  9. </action>
  10. </package>
  11. </struts>

Action类:

  1. package com.shao.action;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.struts2.interceptor.ServletRequestAware;
  8. import org.apache.struts2.interceptor.ServletResponseAware;
  9. import com.google.gson.Gson;
  10. import com.opensymphony.xwork2.ActionSupport;
  11. import com.shao.domain.Music;
  12. public class JSONAction extends ActionSupport implements ServletRequestAware,
  13. ServletResponseAware {
  14. /**
  15. *
  16. */
  17. private static final long serialVersionUID = -3604892179657815531L;
  18. private  HttpServletRequest request;
  19. private  HttpServletResponse  response;
  20. private  String  format;
  21. public String getFormat() {
  22. return format;
  23. }
  24. public void setFormat(String format) {
  25. this.format = format;
  26. }
  27. @Override
  28. public void setServletRequest(HttpServletRequest request) {
  29. // TODO Auto-generated method stub
  30. this.request = request;
  31. }
  32. @Override
  33. public void setServletResponse(HttpServletResponse response) {
  34. // TODO Auto-generated method stub
  35. this.response = response;
  36. }
  37. public  void json(){
  38. List<Music> list = new ArrayList<Music>();
  39. //  JsonArray  jsonArray = new JsonArray();
  40. //  JsonObject jsonObject = new JsonObject();
  41. Gson gson = new  Gson();
  42. Music m1 = new Music();
  43. m1.setId(1);
  44. m1.setAuthor("游鸿明");
  45. m1.setName("白色恋人");
  46. m1.setTime("04:01");
  47. list.add(m1);
  48. Music m2 = new Music();
  49. m2.setId(2);
  50. m2.setAuthor("陈奕迅");
  51. m2.setName("淘汰");
  52. m2.setTime("04:44");
  53. list.add(m2);
  54. Music m3 = new Music();
  55. m3.setId(3);
  56. m3.setAuthor("谢霆锋");
  57. m3.setName("黄种人");
  58. m3.setTime("04:24");
  59. list.add(m3);
  60. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
  61. }.getType();
  62. String beanListToJson = gson.toJson(list,type);
  63. System.out.println("GSON-->"+beanListToJson);
  64. try {
  65. response.setCharacterEncoding("GBK");
  66. //response.setContentType("text/xml;charset=utf-8");
  67. this.response.getWriter().write(beanListToJson);
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. }
  71. }
  72. }

这个Music实体类,android客户端也用到。

  1. package com.shao.domain;
  2. public class Music {
  3. private Integer id;
  4. private String name;
  5. private String time;
  6. private String  author;
  7. public Integer getId() {
  8. return id;
  9. }
  10. public void setId(Integer id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public String getTime() {
  20. return time;
  21. }
  22. public void setTime(String time) {
  23. this.time = time;
  24. }
  25. public String getAuthor() {
  26. return author;
  27. }
  28. public void setAuthor(String author) {
  29. this.author = author;
  30. }
  31. }

访问 http://localhost:8080/Client/getjson.action;结果:

使用Struts2服务端与android交互

二,android客户端:

使用Struts2服务端与android交互

Activity类:

  1. package com.shao.main;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import android.app.Activity;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10. import android.widget.Button;
  11. import android.widget.ListView;
  12. import android.widget.SimpleAdapter;
  13. public class JsonClientActivity extends Activity {
  14. /** Called when the activity is first created. */
  15. private  Button  update;
  16. private ListView listView;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. update = (Button) findViewById(R.id.update);
  22. listView = (ListView) findViewById(R.id.list);
  23. update.setOnClickListener(new OnClickListener() {
  24. @Override
  25. public void onClick(View v) {
  26. // TODO Auto-generated method stub
  27. String urlStr="http://10.0.2.2:8080/Client/getjson.action";
  28. String    result  = GsonUtil.getJson(urlStr);
  29. List<Music>  list = GsonUtil.getListFromJson(result);
  30. List<Map<String,Object>>  data  = getAdapterData(list);
  31. 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});
  32. listView.setAdapter(adapter);
  33. //listView.
  34. }
  35. });
  36. }
  37. private List<Map<String,Object>>  getAdapterData(List  list){
  38. List<Map<String,Object>>  data = new  ArrayList<Map<String,Object>>();
  39. for(int i=0;i<list.size();i++){
  40. Map<String,Object>  map = new HashMap<String, Object>();
  41. Music music= (Music)list.get(i);
  42. map.put("name",music.getName());
  43. map.put("author", music.getAuthor());
  44. map.put("time",music.getTime());
  45. data.add(map);
  46. }
  47. return   data;
  48. }
  49. }
  1. package com.shao.main;
  2. import java.net.URI;
  3. import java.util.List;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.util.EntityUtils;
  10. import com.google.gson.Gson;
  11. public class GsonUtil {
  12. public static  String getJson(String  url){
  13. HttpClient client = new DefaultHttpClient();
  14. HttpPost  request;
  15. try {
  16. request = new HttpPost(new URI(url));
  17. HttpResponse  response  =  client.execute(request);
  18. // 判断请求是否成功
  19. if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功
  20. HttpEntity  entity = response.getEntity();
  21. if(entity!=null){
  22. String beanListToJson = EntityUtils.toString(entity,"GBK");
  23. return beanListToJson;
  24. }
  25. }
  26. } catch (Exception e) {
  27. // TODO: handle exception
  28. }
  29. return  null;
  30. }
  31. public  static  List<Music>  getListFromJson(String json){
  32. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
  33. }.getType();
  34. Gson gson = new Gson();
  35. List<Music>  list  = gson.fromJson(json, type);
  36. return list;
  37. }
  38. }

list.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/name"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:text="name"
  12. />
  13. <TextView
  14. android:id="@+id/author"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_below="@id/name"
  18. android:paddingTop="5px"
  19. android:text="author"
  20. >
  21. </TextView>
  22. <TextView
  23. android:id="@+id/time"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:layout_below="@id/name"
  27. android:layout_alignTop="@id/author"
  28. android:layout_alignParentRight="true"
  29. android:text="time">
  30. </TextView>
  31. </RelativeLayout>

运行结果:

使用Struts2服务端与android交互

主要的交互都是通过goolge的Gson完成