具体要求是:

服务器端得到客户端传递来的数据,并返回给客户端一条json格式的字符串

闲话不多说,直接上代码

首先是服务器端代码:建立一个web工程,导入struts2和json的jar包,并在web.xml中引入struts2

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     id="WebApp_ID" version="3.1">
     <display-name>StrutsForAndroid</display-name>
     <!-- 配置过滤器(即在web中添加struts2) -->
     <filter>
         <filter-name>struts2</filter-name>
         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
         <!-- 配置后缀 <init-param> <param-name>struts.action.extension</param-name>
             <param-value>do,html</param-value> </init-param> -->
     </filter>
     <filter-mapping>
         <filter-name>struts2</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>

     <welcome-file-list>
         <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
 </web-app>

web.xml

然后就是java代码啦

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

     <package name="androidService" namespace="/androidService"
         extends="struts-default">
         <action name="getMessage" class="com.wzy.andriod.actions.AndroidService"
             method="getMsg">
             <result></result>
         </action>
     </package>

     <package name="androidJsonService" namespace="/androidJsonService"
         extends="struts-default">
         <action name="*" class="com.wzy.andriod.actions.AndroidService" method="{1}">
             <result ></result>
         </action>
     </package>

 </struts>

androidService.xml

 package com.wzy.andriod.actions;

 import java.io.PrintWriter;

 import net.sf.json.JSONArray;
 import net.sf.json.JSONObject;

 public class AndroidService extends SuperAction {

     private static final long serialVersionUID = 1L;

     public void getMsg() {

         System.out.println("开始-->");
         try {
             String name = request.getParameter("name");
             System.out.println(name);

             response.setCharacterEncoding("utf-8");
             response.setContentType("text/html");
             PrintWriter writer = response.getWriter();
             writer.print("get到了");

         } catch (Exception e) {
             e.printStackTrace();
         }
     }

     public void getJson() {
         // http://localhost:8080/StrutsForAndroid/androidJsonService/getJson
         System.out.println("getJson开始-->");

         try {
             request.setCharacterEncoding("UTF-8");
             String name = request.getParameter("name");
             String passwd = request.getParameter("passwd");
             System.out.println("-->"+name);
             System.out.println("-->"+passwd);
             JSONArray jsonArray = new JSONArray();

             JSONObject jsonObject = new JSONObject();
             jsonObject.put("id", 1);
             jsonObject.put("name", "小明");
             jsonObject.put("age", 23);

             JSONObject jsonObject1 = new JSONObject();
             jsonObject1.put("id", 2);
             jsonObject1.put("name", "小红");
             jsonObject1.put("age", 12);

             JSONObject jsonObject2 = new JSONObject();
             jsonObject2.put("id", 3);
             jsonObject2.put("name", "Jack");
             jsonObject2.put("age", 100);

             jsonArray.add(0, jsonObject);
             jsonArray.add(1, jsonObject1);
             jsonArray.add(2, jsonObject2);

             response.setCharacterEncoding("UTF-8");
             response.setContentType("text/html");
             PrintWriter writer = response.getWriter();
             // System.out.println(jsonArray.toString());
             writer.print(jsonArray.toString());
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 }

AndroidService.java

 package com.wzy.andriod.actions;

 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import org.apache.struts2.interceptor.ServletRequestAware;
 import org.apache.struts2.interceptor.ServletResponseAware;
 import org.apache.struts2.util.ServletContextAware;

 import com.opensymphony.xwork2.ActionSupport;

 //所有的action动作的父类
 public class SuperAction extends ActionSupport implements ServletRequestAware,
         ServletResponseAware, ServletContextAware {

     private static final long serialVersionUID = 1L;
     /*serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。*/
     protected HttpServletRequest request;
     protected HttpServletResponse response;
     protected ServletContext application;
     protected HttpSession session;

     @Override
     public void setServletContext(ServletContext application) {
         this.application = application;
     }

     @Override
     public void setServletResponse(HttpServletResponse response) {
         this.response = response;
     }

     @Override
     public void setServletRequest(HttpServletRequest request) {
         this.request = request;
         this.session = this.request.getSession();
     }

 }

SuperAction.java

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

     <include file="com/struts2/files/androidService.xml"></include>

 </struts>

struts.xml  

开启tomcat服务器后,通过浏览器访问是如下效果

后台打印结果

以上就是服务端代码部署情况,接下来是安卓客户端代码

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.strutsclient"
     android:versionCode="1"
     android:versionName="1.0" >

     <uses-sdk
         android:minSdkVersion="8"
         android:targetSdkVersion="18" />

     <application
         android:allowBackup="true"
         android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >
         <activity
             android:name="com.example.strutsclient.MainActivity"
             android:label="@string/app_name" >
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />

                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
     </application>
 <uses-permission android:name="android.permission.INTERNET"/>
 </manifest>

AndroidManifest.xml

layout中建立一个用户登录界面

 <?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="vertical" >

     <EditText
         android:id="@+id/name"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:text="123">
     </EditText>

     <EditText
         android:id="@+id/passwd"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="123"
         android:ems="10" />

     <Button
         android:id="@+id/login"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="确定" />

 </LinearLayout>

userlogin.xml

然后就是java代码啦

 package com.example.strutsclient;

 import java.io.BufferedReader;
 import java.io.InputStream;

 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;

 import android.util.Log;

 public class HttpDownloader {

     public String download(String urlStr) {
         StringBuffer sb = new StringBuffer();
         String line = null;
         BufferedReader buffer = null;
         try {
             URL url = new URL(urlStr);// 创建url对象
             HttpURLConnection urlConn = (HttpURLConnection) url
                     .openConnection();// 创建http链接
             Log.i("---->", "----11----");
             InputStream stream = urlConn.getInputStream();
             Log.i("---->", "----22----");
             buffer = new BufferedReader(new InputStreamReader(stream));// io流
             Log.i("---->", "----33----");
             while ((line = buffer.readLine()) != null) {
                 sb.append(line);
             }
         } catch (Exception e) {
             Log.i("---->", e.toString());
             e.printStackTrace();
             return "wrong";
         } finally {
             try {
                 buffer.close();
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
         return sb.toString();
     }

 }

HttpDownloader.java

 package com.example.strutsclient;

 import android.os.Build;
 import android.os.Bundle;
 import android.os.StrictMode;
 import android.annotation.SuppressLint;
 import android.annotation.TargetApi;
 import android.app.Activity;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.Toast;

 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
 @SuppressLint("NewApi")
 public class MainActivity extends Activity {

     EditText name;
     EditText passwd;
     Button login;

     String sname;
     String spasswd;

     @TargetApi(Build.VERSION_CODES.GINGERBREAD)
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.userlogin);
         // 防止android.os.NetworkOnMainThreadException,可使用异步加载或者加入以下代码
         // 因为访问网络会消耗很长时间,安卓会认为死机了,所有出现异常
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads().detectDiskWrites().detectNetwork()
                 .penaltyLog().build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                 .penaltyLog().penaltyDeath().build());

         this.name = (EditText) super.findViewById(R.id.name);
         this.passwd = (EditText) super.findViewById(R.id.passwd);
         this.login = (Button) super.findViewById(R.id.login);
         // Toast.makeText(this, name.getText(), Toast.LENGTH_SHORT).show();

         login.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View arg0) {
                 sname = name.getText().toString();
                 spasswd = passwd.getText().toString();
                 HttpDownloader downloader = new HttpDownloader();
                 String url = "http://172.22.0.1:8080/StrutsForAndroid/androidJsonService/getJson?name="
                         + sname + "&passwd=" + spasswd;
                 String msg = downloader.download(url);
                 // Toast.makeText(this, url, Toast.LENGTH_SHORT).show();

                 login.setText(msg);
             }
         });
     }

 }

MainActivity.java

response发送不同类型的数据:

public static void writeJson(HttpServletResponse response, String text) {
  render(response, "application/json;charset=UTF-8", text);
}

public static void writeXml(HttpServletResponse response, String text) {
  render(response, "text/xml;charset=UTF-8", text);
}

public static void writeText(HttpServletResponse response, String text) {
  render(response, "text/plain;charset=UTF-8", text);
}

public static void render(HttpServletResponse response, String contentType,
String text) {
  response.setContentType(contentType);
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
try {
  response.getWriter().write(text);
} catch (IOException e) {
  //log.error(e.getMessage(), e);
}
}

Android与Struts2简单json通信的更多相关文章

  1. struts2 + jquery + json 简单的前后台信息交互

    ajax 是一种客户端与服务器端异步请求的交互技术.相比同步请求,大大提高了信息交互的速度和效率.是当下非常实用和流行的技术. 这里简单的说明 struts2 + jquery + json 下的 信 ...

  2. 深入了解Struts2返回JSON数据的原理

    首先来看一下JSON官方对于"JSON"的解释: JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析 ...

  3. (转)Struts2返回JSON数据的具体应用范例

    转载自 yshjava的个人博客主页 <Struts2返回JSON数据的具体应用范例> 早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具 ...

  4. Struts2返回JSON数据的具体应用范例

    早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具体应用了,但苦于一直忙于工作难以抽身,渐渐的也淡忘了此事.直到前两天有同事在工作中遇到这个问题,来找 ...

  5. Struts2返回JSON数据的具体应用范…

    Struts2返回JSON数据的具体应用范例 博客分类: Struts2 Struts2JSON  早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具 ...

  6. 【转】Struts2中json插件的使用

    配置注意点: 在原有Struts2框架jar包的引入下,需要额外多加一个Json的插件包(struts2-json-plugin-2.3.7.jar) 在struts.xml配置文件中,包需要继承js ...

  7. struts2 + ajax + json的结合使用,实例讲解

    struts2用response怎么将json值返回到页面javascript解析,这里介绍一个struts2与json整合后包的用法. 1.准备工作 ①ajax使用Jquery:jquery-1.4 ...

  8. (转)Struts2返回JSON对象的方法总结

    转自:http://kingxss.iteye.com/blog/1622455 如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选 ...

  9. Android BLE开发——Android手机与BLE终端通信初识

    蓝牙BLE官方Demo下载地址:   http://download.csdn.net/detail/lqw770737185/8116019参考博客地址:    http://www.eoeandr ...

随机推荐

  1. 吉日嘎拉C#快速开发平台V4.0到V4.2升级记

    目前我用的版本是4.0的,也有近2年没更新了,狠了狠心升级一下,没想到真的行动起来,也没那么难! 用了3天时间,将吉日嘎拉的代码升级到了4.2版本,并让原来的DotNet.WebApplication ...

  2. php strtotime 在32位操作系统下的限制

    php strtotime 在32位操作系统下的限制 <?php class DateHelper{ /** * 在32位操作系统下,超过 2038-01-19 03:14:07 ,会溢出 * ...

  3. placeholder的样式设置

    在input框中有时想将输入的字和placeholder设为不同的颜色或其它效果,这时就可以用以下代码来对placeholder进行样式设置了. ::-webkit-input-placeholder ...

  4. MyEclipse10查看Struts2源码及Javadoc文档

    1:查看Struts2源码 (1):Referenced Libraries >struts2-core-2.1.6.jar>右击>properties. (2):Java Sour ...

  5. 软件公司为何要放弃MongoDB?

    本文转至:http://database.51cto.com/art/201503/469510_all.htm(只作转载, 不代表本站和博主同意文中观点或证实文中信息) Olery成立于2010年, ...

  6. 悟透JavaScript(理解JS面向对象的好文章)

    引子 编程世界里只存在两种基本元素,一个是数据,一个是代码.编程世界就是在数据和代码千丝万缕的纠缠中呈现出无限的生机和活力. 数据天生就是文静的,总想保持自己固有的本色:而代码却天生活泼,总想改变这个 ...

  7. (转)SqlServer索引及优化详解(1)

    (一)深入浅出理解索引结构         实际上,您可以把索引理解为一种特殊的目录.微软的SQL SERVER提供了两种索引:聚集索引(clustered index,也称聚类索引.簇集索引)和非聚 ...

  8. js instanceof

    a instanceof b: 1,首先a不是对象,返回false,b的原型不是对象抛出TypeError 2,取得b的prototype标记为bp,对a的原型链做循环,令ap为当前原型,如果ap与b ...

  9. 网络分析之Pgrouting(转载)

    网上关于Pgrouting的使用介绍太简单了,这里想详细的总结一下Pgrouting的使用,其实主要参照官方文档:http://workshop.pgrouting.org/ 第一步:配置环境 关于P ...

  10. 0x80040E14 Caused by Max Url Length bug

    We get a case when the customer access a SharePoint site, he meet an error on SharePoint. 0x80040E14 ...