使用Struts2服务端与android交互
16lz
2021-01-23
转自:http://www.cnblogs.com/android-html5/archive/2011/09/25/2534107.html
android--使用Struts2服务端与android交互
一,服务器端:
首先搭建struts2的环境,导入必要的类库。
web.xml文件:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appversion="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文件:
- <?xmlversion="1.0"encoding="GBK"?>
- <!DOCTYPEstrutsPUBLIC
- "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <packagename="testjson"<spanstyle="color:#ff0000;">extends="json-default"</span>>
- <actionname="getjson"class="com.shao.action.JSONAction"method="json">
- <resulttype="json"></result>
- </action>
- </package>
- </struts>
Action类:
- packagecom.shao.action;
- importjava.io.IOException;
- importjava.util.ArrayList;
- importjava.util.List;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importorg.apache.struts2.interceptor.ServletRequestAware;
- importorg.apache.struts2.interceptor.ServletResponseAware;
- importcom.google.gson.Gson;
- importcom.opensymphony.xwork2.ActionSupport;
- importcom.shao.domain.Music;
- publicclassJSONActionextendsActionSupportimplementsServletRequestAware,
- ServletResponseAware{
- /**
- *
- */
- privatestaticfinallongserialVersionUID=-3604892179657815531L;
- privateHttpServletRequestrequest;
- privateHttpServletResponseresponse;
- privateStringformat;
- publicStringgetFormat(){
- returnformat;
- }
- publicvoidsetFormat(Stringformat){
- this.format=format;
- }
- @Override
- publicvoidsetServletRequest(HttpServletRequestrequest){
- //TODOAuto-generatedmethodstub
- this.request=request;
- }
- @Override
- publicvoidsetServletResponse(HttpServletResponseresponse){
- //TODOAuto-generatedmethodstub
- this.response=response;
- }
- publicvoidjson(){
- List<Music>list=newArrayList<Music>();
- //JsonArrayjsonArray=newJsonArray();
- //JsonObjectjsonObject=newJsonObject();
- Gsongson=newGson();
- Musicm1=newMusic();
- m1.setId(1);
- m1.setAuthor("游鸿明");
- m1.setName("白色恋人");
- m1.setTime("04:01");
- list.add(m1);
- Musicm2=newMusic();
- m2.setId(2);
- m2.setAuthor("陈奕迅");
- m2.setName("淘汰");
- m2.setTime("04:44");
- list.add(m2);
- Musicm3=newMusic();
- m3.setId(3);
- m3.setAuthor("谢霆锋");
- m3.setName("黄种人");
- m3.setTime("04:24");
- list.add(m3);
- java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<Music>>(){
- }.getType();
- StringbeanListToJson=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(IOExceptione){
- e.printStackTrace();
- }
- }
- }
- packagecom.shao.domain;
- publicclassMusic{
- privateIntegerid;
- privateStringname;
- privateStringtime;
- privateStringauthor;
- publicIntegergetId(){
- returnid;
- }
- publicvoidsetId(Integerid){
- this.id=id;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetTime(){
- returntime;
- }
- publicvoidsetTime(Stringtime){
- this.time=time;
- }
- publicStringgetAuthor(){
- returnauthor;
- }
- publicvoidsetAuthor(Stringauthor){
- this.author=author;
- }
- }
访问 http://localhost:8080/Client/getjson.action;结果:
二,android客户端:
Activity类:
- packagecom.shao.main;
- importjava.util.ArrayList;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.ListView;
- importandroid.widget.SimpleAdapter;
- publicclassJsonClientActivityextendsActivity{
- /**Calledwhentheactivityisfirstcreated.*/
- privateButtonupdate;
- privateListViewlistView;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- update=(Button)findViewById(R.id.update);
- listView=(ListView)findViewById(R.id.list);
- update.setOnClickListener(newOnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- StringurlStr="http://10.0.2.2:8080/Client/getjson.action";
- Stringresult=GsonUtil.getJson(urlStr);
- List<Music>list=GsonUtil.getListFromJson(result);
- List<Map<String,Object>>data=getAdapterData(list);
- SimpleAdapteradapter=newSimpleAdapter(JsonClientActivity.this,data,R.layout.list,newString[]{"name","author","time"},newint[]{R.id.name,R.id.author,R.id.time});
- listView.setAdapter(adapter);
- //listView.
- }
- });
- }
- privateList<Map<String,Object>>getAdapterData(Listlist){
- List<Map<String,Object>>data=newArrayList<Map<String,Object>>();
- for(inti=0;i<list.size();i++){
- Map<String,Object>map=newHashMap<String,Object>();
- Musicmusic=(Music)list.get(i);
- map.put("name",music.getName());
- map.put("author",music.getAuthor());
- map.put("time",music.getTime());
- data.add(map);
- }
- returndata;
- }
- }
- packagecom.shao.main;
- importjava.net.URI;
- importjava.util.List;
- importorg.apache.http.HttpEntity;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.client.HttpClient;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.impl.client.DefaultHttpClient;
- importorg.apache.http.util.EntityUtils;
- importcom.google.gson.Gson;
- publicclassGsonUtil{
- publicstaticStringgetJson(Stringurl){
- HttpClientclient=newDefaultHttpClient();
- HttpPostrequest;
- try{
- request=newHttpPost(newURI(url));
- HttpResponseresponse=client.execute(request);
- //判断请求是否成功
- if(response.getStatusLine().getStatusCode()==200){//200表示请求成功
- HttpEntityentity=response.getEntity();
- if(entity!=null){
- StringbeanListToJson=EntityUtils.toString(entity,"GBK");
- returnbeanListToJson;
- }
- }
- }catch(Exceptione){
- //TODO:handleexception
- }
- returnnull;
- }
- publicstaticList<Music>getListFromJson(Stringjson){
- java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<Music>>(){
- }.getType();
- Gsongson=newGson();
- List<Music>list=gson.fromJson(json,type);
- returnlist;
- }
- }
list.xml
- <?xmlversion="1.0"encoding="utf-8"?>
- <RelativeLayoutxmlns: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完成
更多相关文章
- android 拍照+从手机相册选择返回图片到imagview
- Android 获取系统相册中的所有图片
- Android之背景图片设置为重复而不是默认的拉伸
- Android 国际化,文本国际化,图片国际化
- Android 单击图片切换效果
- Android高仿网易新闻客户端之动态添加标签
- Android 之多点触摸 手势拉伸放大缩小图片 并在ImageView上画圆