Android与Struts2简单json通信
具体要求是:
服务器端得到客户端传递来的数据,并返回给客户端一条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通信的更多相关文章
- struts2 + jquery + json 简单的前后台信息交互
ajax 是一种客户端与服务器端异步请求的交互技术.相比同步请求,大大提高了信息交互的速度和效率.是当下非常实用和流行的技术. 这里简单的说明 struts2 + jquery + json 下的 信 ...
- 深入了解Struts2返回JSON数据的原理
首先来看一下JSON官方对于"JSON"的解释: JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析 ...
- (转)Struts2返回JSON数据的具体应用范例
转载自 yshjava的个人博客主页 <Struts2返回JSON数据的具体应用范例> 早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具 ...
- Struts2返回JSON数据的具体应用范例
早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具体应用了,但苦于一直忙于工作难以抽身,渐渐的也淡忘了此事.直到前两天有同事在工作中遇到这个问题,来找 ...
- Struts2返回JSON数据的具体应用范…
Struts2返回JSON数据的具体应用范例 博客分类: Struts2 Struts2JSON 早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具 ...
- 【转】Struts2中json插件的使用
配置注意点: 在原有Struts2框架jar包的引入下,需要额外多加一个Json的插件包(struts2-json-plugin-2.3.7.jar) 在struts.xml配置文件中,包需要继承js ...
- struts2 + ajax + json的结合使用,实例讲解
struts2用response怎么将json值返回到页面javascript解析,这里介绍一个struts2与json整合后包的用法. 1.准备工作 ①ajax使用Jquery:jquery-1.4 ...
- (转)Struts2返回JSON对象的方法总结
转自:http://kingxss.iteye.com/blog/1622455 如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选 ...
- Android BLE开发——Android手机与BLE终端通信初识
蓝牙BLE官方Demo下载地址: http://download.csdn.net/detail/lqw770737185/8116019参考博客地址: http://www.eoeandr ...
随机推荐
- csharp: Oracle Stored Procedure DAL using ODP.NET
paging : http://www.codeproject.com/Articles/44858/Custom-Paging-GridView-in-ASP-NET-Oracle https:// ...
- should be mapped with insert="false" update="false
SSH项目出现了 should be mapped with insert="false" update="false 错误,仔细检查后发现,是两个不同的属性映射了表中的 ...
- UVALive 6911---Double Swords(贪心+树状数组(或集合))
题目链接 https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...
- python基础之数据类型(一)
Python3 数字(Number) 定义:a=1 特性: 1.只能存放一个值 2.一经定义,不可更改 3.直接访问 分类:整型,长整型,布尔,浮点,复数 python2.*与python3.*关于整 ...
- REST服务介绍二
之前一篇文章写过REST服务介绍, 今天再次来自回顾一下. REST是一种架构风格. 首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是 HTTP 规范 ...
- JSTL标签功能集锦
1.<fmt:parseNumber integerOnly="true" value="2/3" /> 结果为0 功能:fmt:parseNumb ...
- Bootstrap组件之响应式导航条
响应式导航条:在PC和平板中默认要显示所有的内容:但在手机中导航条中默认只显示“LOGO/Brand”,以及一个“菜单折叠展开按钮”,只有单击折叠按钮后才显示所有的菜单项. 基础class: .nav ...
- NSString 的常用操作
NSString *testStr01=@"HelloWord"; NSString *testStr02=[testStr01 substringToIndex:];//取头(从 ...
- SDWebImage添加header
title: SDWebImage添加headerdate: 2016-03-07 17:32:57tags: SDWebImagecategories: IOS keywords: SDWebIma ...
- iOS开发之功能模块--推送之坑问题解决
不管想不想看我后面再开发中总结的经验,但是很值得推荐一位大神写的关于苹果推送,很多内容哦:http://www.cnblogs.com/qiqibo/category/408304.html 苹果开发 ...