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

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

一,服务器端:

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

web.xml文件:

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appversion="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. <?xmlversion="1.0"encoding="GBK"?>
  2. <!DOCTYPEstrutsPUBLIC
  3. "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <packagename="testjson"<spanstyle="color:#ff0000;">extends="json-default"</span>>
  7. <actionname="getjson"class="com.shao.action.JSONAction"method="json">
  8. <resulttype="json"></result>
  9. </action>
  10. </package>
  11. </struts>

Action类:

  1. packagecom.shao.action;
  2. importjava.io.IOException;
  3. importjava.util.ArrayList;
  4. importjava.util.List;
  5. importjavax.servlet.http.HttpServletRequest;
  6. importjavax.servlet.http.HttpServletResponse;
  7. importorg.apache.struts2.interceptor.ServletRequestAware;
  8. importorg.apache.struts2.interceptor.ServletResponseAware;
  9. importcom.google.gson.Gson;
  10. importcom.opensymphony.xwork2.ActionSupport;
  11. importcom.shao.domain.Music;
  12. publicclassJSONActionextendsActionSupportimplementsServletRequestAware,
  13. ServletResponseAware{
  14. /**
  15. *
  16. */
  17. privatestaticfinallongserialVersionUID=-3604892179657815531L;
  18. privateHttpServletRequestrequest;
  19. privateHttpServletResponseresponse;
  20. privateStringformat;
  21. publicStringgetFormat(){
  22. returnformat;
  23. }
  24. publicvoidsetFormat(Stringformat){
  25. this.format=format;
  26. }
  27. @Override
  28. publicvoidsetServletRequest(HttpServletRequestrequest){
  29. //TODOAuto-generatedmethodstub
  30. this.request=request;
  31. }
  32. @Override
  33. publicvoidsetServletResponse(HttpServletResponseresponse){
  34. //TODOAuto-generatedmethodstub
  35. this.response=response;
  36. }
  37. publicvoidjson(){
  38. List<Music>list=newArrayList<Music>();
  39. //JsonArrayjsonArray=newJsonArray();
  40. //JsonObjectjsonObject=newJsonObject();
  41. Gsongson=newGson();
  42. Musicm1=newMusic();
  43. m1.setId(1);
  44. m1.setAuthor("游鸿明");
  45. m1.setName("白色恋人");
  46. m1.setTime("04:01");
  47. list.add(m1);
  48. Musicm2=newMusic();
  49. m2.setId(2);
  50. m2.setAuthor("陈奕迅");
  51. m2.setName("淘汰");
  52. m2.setTime("04:44");
  53. list.add(m2);
  54. Musicm3=newMusic();
  55. m3.setId(3);
  56. m3.setAuthor("谢霆锋");
  57. m3.setName("黄种人");
  58. m3.setTime("04:24");
  59. list.add(m3);
  60. java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<Music>>(){
  61. }.getType();
  62. StringbeanListToJson=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(IOExceptione){
  69. e.printStackTrace();
  70. }
  71. }
  72. }

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

  1. packagecom.shao.domain;
  2. publicclassMusic{
  3. privateIntegerid;
  4. privateStringname;
  5. privateStringtime;
  6. privateStringauthor;
  7. publicIntegergetId(){
  8. returnid;
  9. }
  10. publicvoidsetId(Integerid){
  11. this.id=id;
  12. }
  13. publicStringgetName(){
  14. returnname;
  15. }
  16. publicvoidsetName(Stringname){
  17. this.name=name;
  18. }
  19. publicStringgetTime(){
  20. returntime;
  21. }
  22. publicvoidsetTime(Stringtime){
  23. this.time=time;
  24. }
  25. publicStringgetAuthor(){
  26. returnauthor;
  27. }
  28. publicvoidsetAuthor(Stringauthor){
  29. this.author=author;
  30. }
  31. }

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

二,android客户端:

Activity类:

  1. packagecom.shao.main;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importjava.util.Map;
  6. importandroid.app.Activity;
  7. importandroid.os.Bundle;
  8. importandroid.view.View;
  9. importandroid.view.View.OnClickListener;
  10. importandroid.widget.Button;
  11. importandroid.widget.ListView;
  12. importandroid.widget.SimpleAdapter;
  13. publicclassJsonClientActivityextendsActivity{
  14. /**Calledwhentheactivityisfirstcreated.*/
  15. privateButtonupdate;
  16. privateListViewlistView;
  17. @Override
  18. publicvoidonCreate(BundlesavedInstanceState){
  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(newOnClickListener(){
  24. @Override
  25. publicvoidonClick(Viewv){
  26. //TODOAuto-generatedmethodstub
  27. StringurlStr="http://10.0.2.2:8080/Client/getjson.action";
  28. Stringresult=GsonUtil.getJson(urlStr);
  29. List<Music>list=GsonUtil.getListFromJson(result);
  30. List<Map<String,Object>>data=getAdapterData(list);
  31. SimpleAdapteradapter=newSimpleAdapter(JsonClientActivity.this,data,R.layout.list,newString[]{"name","author","time"},newint[]{R.id.name,R.id.author,R.id.time});
  32. listView.setAdapter(adapter);
  33. //listView.
  34. }
  35. });
  36. }
  37. privateList<Map<String,Object>>getAdapterData(Listlist){
  38. List<Map<String,Object>>data=newArrayList<Map<String,Object>>();
  39. for(inti=0;i<list.size();i++){
  40. Map<String,Object>map=newHashMap<String,Object>();
  41. Musicmusic=(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. returndata;
  48. }
  49. }

  1. packagecom.shao.main;
  2. importjava.net.URI;
  3. importjava.util.List;
  4. importorg.apache.http.HttpEntity;
  5. importorg.apache.http.HttpResponse;
  6. importorg.apache.http.client.HttpClient;
  7. importorg.apache.http.client.methods.HttpPost;
  8. importorg.apache.http.impl.client.DefaultHttpClient;
  9. importorg.apache.http.util.EntityUtils;
  10. importcom.google.gson.Gson;
  11. publicclassGsonUtil{
  12. publicstaticStringgetJson(Stringurl){
  13. HttpClientclient=newDefaultHttpClient();
  14. HttpPostrequest;
  15. try{
  16. request=newHttpPost(newURI(url));
  17. HttpResponseresponse=client.execute(request);
  18. //判断请求是否成功
  19. if(response.getStatusLine().getStatusCode()==200){//200表示请求成功
  20. HttpEntityentity=response.getEntity();
  21. if(entity!=null){
  22. StringbeanListToJson=EntityUtils.toString(entity,"GBK");
  23. returnbeanListToJson;
  24. }
  25. }
  26. }catch(Exceptione){
  27. //TODO:handleexception
  28. }
  29. returnnull;
  30. }
  31. publicstaticList<Music>getListFromJson(Stringjson){
  32. java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<Music>>(){
  33. }.getType();
  34. Gsongson=newGson();
  35. List<Music>list=gson.fromJson(json,type);
  36. returnlist;
  37. }
  38. }

list.xml

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns: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>

运行结果:

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

更多相关文章

  1. 2010 Linux Journal读者选择奖揭晓
  2. 基于Apache mina 的android 客户端tcp长连接实现
  3. Android(安卓)近百个项目的源代码,覆盖Android开发的每个领域
  4. android开源框架源码分析:Okhttp
  5. Android:开发中遇到的异常Error解析
  6. Android高仿网易新闻客户端之动态添加标签
  7. 基于TCP和多线程实现无线鼠标键盘-Socket(2)
  8. Android(安卓)近百个项目的源代码,覆盖Android开发的每个领域
  9. Android实现文件上传功能(接收端用strust2)

随机推荐

  1. Windows下git下载android source
  2. android ndk 使用第三方静态库
  3. 【android】checkedTextView形成自定义Li
  4. Android(安卓)API 中文 (55) —— ListAdap
  5. 疯狂android讲义学习总结---TextView
  6. 加速 Android(安卓)开发的五大开源网站
  7. Android界面开发推荐颜色
  8. Android(安卓)EventBus的使用
  9. Android(安卓)SQLite Shell
  10. Android(安卓)AppWidget系统框架