struts2服务端与android交互
生活随笔
收集整理的這篇文章主要介紹了
struts2服务端与android交互
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文主要包括以下內容
服務器端代碼
package com.easyway.json.android;import java.util.HashMap; import java.util.Map;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware;import com.opensymphony.xwork2.ActionSupport;/*** 在android中有時候我們不需要用到本機的SQLite數據庫提供數據,更多的時候是從網絡上獲取數據,* 那么Android怎么從服務器端獲取數據呢?有很多種,歸納起來有*一:基于Http協議獲取數據方法。*二:基于SAOP協議獲取數據方法,*那么我們的這篇文章主要是將關于使用Http協議獲取服務器端數據,*這里我們采取的服務器端技術為java,框架為Struts2,或者可以有Servlet,又或者可直接從JSP頁面中獲取數據。*那么,接下來我們便開始這一路程:*首先:編寫服務器端方法,我這里采用的MVC框架是Struts2,目的很單純,就是為了以后做個完整的商業項目,*技術配備為:android+SSH。當然,篇幅有限,我這里就直接用Strtus2而已。*服務器端:新建WebProject ,選擇Java ee 5.0.*為了給項目添加Struts2的支持,我們必須導入Struts2的一些類庫,如下即可(有些jar包是不必的,但是我們后來擴展可能是要使用到的,就先弄進去):*xwork-core-2.2.1.1.jar struts2-core-2.2.1.1.jar commons-logging-1.0.4.jar freemarker-2.3.16.jar*ognl-3.0.jar javassist-3.7.ga.jar commons-ileupload.jar commons-io.jar json-lib-2.1-jdk15.jar *處理JSON格式數據要使用到 struts2-json-plugin-2.2.1.1.jar * 基于struts2的json插件.* * * 采用接口注入的方式注入HttpServletRequest,HttpServletResponse對象* * @author longgangbai**/ public class LoginAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {/** * */private static final long serialVersionUID = 1L;HttpServletRequest request;HttpServletResponse response;private String userName;private String password;public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public void setServletRequest(HttpServletRequest request) {this.request = request;}public void setServletResponse(HttpServletResponse response) {this.response = response;}/*** 模擬用戶登錄的業務*/public void login() {try {//如果不采用接口注入的方式的獲取HttpServletRequest,HttpServletResponse的方式// HttpServletRequest request =ServletActionContext.getRequest();// HttpServletResponse response=ServletActionContext.getResponse();this.response.setContentType("text/json;charset=utf-8");this.response.setCharacterEncoding("UTF-8");//JSONObject json=new JSONObject(); Map<String,String> json=new HashMap<String,String>();if ("admin".equals(userName)&&"123456".equals(password)) {json.put("message", "歡迎管理員登陸");} else if ((!"admin".equals(userName))&&"123456".equals(password)) {json.put("message", "歡迎"+userName+"登陸!");} else {json.put("message", "非法登陸信息!");}byte[] jsonBytes = json.toString().getBytes("utf-8");response.setContentLength(jsonBytes.length);response.getOutputStream().write(jsonBytes);response.getOutputStream().flush();response.getOutputStream().close();} catch (Exception e) {e.printStackTrace();}} }struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- setting encoding,DynamicMethod,language <constant name="struts.custom.i18n.resources" value="messageResource"></constant> --><constant name="struts.i18n.encoding" value="UTF-8"/><constant name="struts.enable.DynamicMethodInvocation" value="true"/><!-- add package here extends="struts-default"--><package name="default" extends="json-default"><!--需要將struts-default改為--><action name="login" class="com.easyway.json.android.LoginAction"method="login"><result type="json"/><!--返回值類型設置為json,不設置返回頁面--></action></package> </struts>ajax測試頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax調用web服務</title> <script type="text/javascript"> var xmlHttpReq; //用于保存XMLHttpRequest對象的全局變量//用于創建XMLHttpRequest對象 function createXmlHttp() {//根據window.XMLHttpRequest對象是否存在使用不同的創建方式 // if (window.XMLHttpRequest) { // xmlHttp = new XMLHttpRequest(); //FireFox、Opera等瀏覽器支持的創建方式 // } else { // xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE瀏覽器支持的創建方式 // }if (window.ActiveXObject) {xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");} else if (window.XMLHttpRequest) {xmlHttpReq = new XMLHttpRequest();} }function loadAjax() {createXmlHttp(); //創建XmlHttpRequest對象var url="http://localhost:8080/AndroidStruts2JSON/login.action?userName=admin&password=123456&date="+new Date();//xmlHttpReq.open("get", encodeURI(encodeURI(url+param,"UTF-8"),"UTF-8"), true);xmlHttpReq.open("get", encodeURI(encodeURI(url,"UTF-8"),"UTF-8"), true);//上傳圖片xmlHttpReq.setrequestheader("content-type","application/x-www-form-urlencoded");//post提交設置項xmlHttpReq.onreadystatechange = loadCallback; //IE這里設置回調函數xmlHttpReq.send(null);}function loadCallback() {//alert(xmlHttpReq.readyState);if (xmlHttpReq.readyState == 4) {alert("aa");//if(xmlHttpReq.status==200){document.getElementById("contentDiv").innerHTML=xmlHttpReq.responseText;//}} }</script><body> <div id="contentTypeDiv"> </div> <br/><br/> <div id="contentDiv"> </div><input type="button" value="調用" onclick="loadAjax()"></body> </head> </html>手機代碼
package com.easyway.android.json;import java.io.IOException;import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject;import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; /*** 在現在開發的項目中采用Android+REST WebService服務方式開發的手機平臺很少采用* soap協議這種方式,主要soap協議解析問題,增加了代碼量。* * * 在android中有時候我們不需要用到本機的SQLite數據庫提供數據,更多的時候是從網絡上獲取數據,* 那么Android怎么從服務器端獲取數據呢?有很多種,歸納起來有* 一:基于Http協議獲取數據方法。* 二:基于SAOP協議獲取數據方法**備注:在網絡有關的問題最好添加以下兩項:* 1.線程和虛擬機策略* ///在Android2.2以后必須添加以下代碼 * //本應用采用的Android4.0 * //設置線程的策略 * StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() * .detectDiskReads() * .detectDiskWrites() * .detectNetwork() // or .detectAll() for all detectable problems * .penaltyLog() * .build()); * //設置虛擬機的策略 * StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() * .detectLeakedSqlLiteObjects() * //.detectLeakedClosableObjects() * .penaltyLog() * .penaltyDeath() * .build()); * 2.可以訪問網絡的權限: * 即AndroidManifest.xml中配置: * <uses-permission android:name="android.permission.INTERNET"/>** * @author longgangbai* **/ public class AndroidHttpJSONActivity extends Activity {private static String processURL="http://192.168.1.130:8080/AndroidStruts2JSON/login.action?";private EditText txUserName;private EditText txPassword;private Button btnLogin;/*** Called when the activity is first created.*/@Overridepublic void onCreate(Bundle savedInstanceState) {///在Android2.2以后必須添加以下代碼//本應用采用的Android4.0//設置線程的策略StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); //設置虛擬機的策略StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() //.detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build());super.onCreate(savedInstanceState);//設置頁面布局setContentView(R.layout.main);//設置初始化視圖initView();//設置事件監聽器方法setListener();}/*** 創建初始化視圖的方法*/private void initView() {btnLogin=(Button)findViewById(R.id.btnLogin);txPassword=(EditText)findViewById(R.id.txtPassword);txUserName=(EditText)findViewById(R.id.txtUserName);}/*** 設置事件的監聽器的方法*/private void setListener() {btnLogin.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String userName=txUserName.getText().toString();String password=txPassword.getText().toString();loginRemoteService(userName,password);}});}/*** 獲取Struts2 Http 登錄的請求信息* @param userName* @param password*/public void loginRemoteService(String userName,String password){String result=null;try {//創建一個HttpClient對象HttpClient httpclient = new DefaultHttpClient();//遠程登錄URLprocessURL=processURL+"userName="+userName+"&password="+password;Log.d("遠程URL", processURL);//創建HttpGet對象HttpGet request=new HttpGet(processURL);//請求信息類型MIME每種響應類型的輸出(普通文本、html 和 XML,json)。允許的響應類型應當匹配資源類中生成的 MIME 類型//資源類生成的 MIME 類型應當匹配一種可接受的 MIME 類型。如果生成的 MIME 類型和可接受的 MIME 類型不 匹配,那么將//生成 com.sun.jersey.api.client.UniformInterfaceException。例如,將可接受的 MIME 類型設置為 text/xml,而將//生成的 MIME 類型設置為 application/xml。將生成 UniformInterfaceException。request.addHeader("Accept","text/json");//獲取響應的結果HttpResponse response =httpclient.execute(request);//獲取HttpEntityHttpEntity entity=response.getEntity();//獲取響應的結果信息String json =EntityUtils.toString(entity,"UTF-8");//JSON的解析過程if(json!=null){JSONObject jsonObject=new JSONObject(json);result=jsonObject.get("message").toString();}if(result==null){json="登錄失敗請重新登錄";}//創建提示框提醒是否登錄成功AlertDialog.Builder builder=new Builder(AndroidHttpJSONActivity.this);builder.setTitle("提示").setMessage(result).setPositiveButton("確定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).create().show();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }參考鏈接
Android+struts2+JSON方式的手機開發 - topMan’blog - ITeye技術網站
效果如下
android從struts2服務器獲取list數據
參考鏈接
android–使用Struts2服務端與android交互 - android開發實例 - 博客園
效果如下
android上傳數據到struts2服務器
android端代碼
package com.zj.wifitest;import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL;import org.json.JSONObject;import android.app.Activity; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void click(View view){run();}public void run() {new Thread() {@Overridepublic void run() {try {HttpURLConnection conn = null;String content = "";try {// 為了測試取消連接// Thread.sleep(5000);// http聯網可以用httpClient或java.net.url// URL url = new URL(////// "http://115.28.34.52:8080/Car_Experiment/carInsert_insert_info.action");// carInsert_insert_info.action"URL url = new URL("http://120.27.126.68:8080/CarServer/transAction");conn = (HttpURLConnection) url.openConnection();conn.setDoInput(true);conn.setDoOutput(true);conn.setConnectTimeout(1000 * 30);conn.setReadTimeout(1000 * 30);conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");OutputStream output = conn.getOutputStream();JSONObject jsonObject = new JSONObject();jsonObject.put("0C", "0A0B");jsonObject.put("0D", "0B");jsonObject.put("10", "0A0B");jsonObject.put("11", "0B");//jsonObject.put("13", "0B"); // jsonObject.put("14", "0A0B"); // jsonObject.put("15", "0A0B"); // jsonObject.put("16", "0A0B"); // jsonObject.put("17", "0A0B"); // jsonObject.put("18", "0A0B"); // jsonObject.put("19", "0A0B"); // jsonObject.put("1A", "0A0B"); // jsonObject.put("1B", "0A0B");jsonObject.put("2F", "0A0B");jsonObject.put("02", "0A0B");System.out.println(jsonObject.toString());output.write(jsonObject.toString().getBytes());output.flush();output.close();int responseCode = conn.getResponseCode();Log.i("test", "responseCode"+responseCode);InputStream in = conn.getInputStream();System.out.println("responseCode=" + responseCode);if (responseCode == HttpURLConnection.HTTP_OK) {System.out.println("responseCode=" + HttpURLConnection.HTTP_OK);Log.i("test", "successed");// InputStreamReader reader = new// InputStreamReader(in,charSet);BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = null;while ((line = reader.readLine()) != null) {content += line;}System.out.println("result:" + content);}in.close();} catch (Exception e) {e.printStackTrace();} finally {conn.disconnect();conn = null;}} catch (Exception e) {e.printStackTrace();}}}.start();} }服務器端代碼
package whu.zhengrenjie.Action;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;import whu.zhengrenjie.Model.SimpleService; import whu.zhengrenjie.Util.Util;import com.opensymphony.xwork2.ActionSupport;public class TransDataAction extends ActionSupport {private SimpleService simpleService;private BufferedReader reader;public SimpleService getSimpleService() {return simpleService;}public void setSimpleService(SimpleService simpleService) {this.simpleService = simpleService;}@Overridepublic String execute() throws Exception {// TODO Auto-generated method stubif (Util.TEST) {String test;JSONObject jsonObject = new JSONObject();jsonObject.put("0C", "0000");jsonObject.put("0D", "00");jsonObject.put("10", "0000");jsonObject.put("11", "00");jsonObject.put("2F", "00");jsonObject.put("02", "12345678");test = jsonObject.toString();System.out.println("----------------------" + test);simpleService.insert(test);} else {try {String request = "";String temp = "";System.out.println("herrrrrrrrrrrrre");reader = new BufferedReader(new InputStreamReader(ServletActionContext.getRequest().getInputStream(),"UTF-8"));while ((temp = reader.readLine()) != null) {request += temp;}simpleService.insert(request);} catch (IOException e) {// TODO Auto-generated catch blockce.printStackTrace();} finally {reader.close();}}return super.execute();} }SimpleService
package whu.zhengrenjie.Model;import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;import net.sf.json.JSONObject; import whu.zhengrenjie.DAO.SimpleDAO; import whu.zhengrenjie.PO.RunTimePO; import whu.zhengrenjie.Util.Util;public class SimpleService {private int count = 0;private SimpleDAO simpleDAO;private RunTimePO runTimePO;private JSONObject jsonObject;public SimpleDAO getSimpleDAO() {return simpleDAO;}public void setSimpleDAO(SimpleDAO simpleDAO) {this.simpleDAO = simpleDAO;}public RunTimePO getRunTimePO() {return runTimePO;}public void setRunTimePO(RunTimePO runTimePO) {this.runTimePO = runTimePO;}public void insert(String requestStr) {jsonObject = JSONObject.fromObject(requestStr);String rpmStr = (String) jsonObject.get("0C");if (!rpmStr.contains("0000")) {double rpm = Integer.parseInt(rpmStr, 16) / 4; runTimePO.setRpm(rpm);if (Util.DEBUG) {System.out.println(count++);}} else {runTimePO.setRpm(0);}String speedStr = (String) jsonObject.get("0D");if (!speedStr.contains("00")) {double speed = Integer.parseInt(speedStr, 16);runTimePO.setSpeed(speed);if (Util.DEBUG) {System.out.println(count++);}} else {runTimePO.setSpeed(0);}String airSpeedStr = (String) jsonObject.get("10");if (!airSpeedStr.contains("0000")) {double airSpeed = Integer.parseInt(airSpeedStr, 16) / 100;runTimePO.setAirSpeed(airSpeed);if (Util.DEBUG) {System.out.println(count++);}} else {runTimePO.setAirSpeed(0);}String throttleStr = (String) jsonObject.get("11");if (!throttleStr.contains("00")) {double throttle_1 = Integer.parseInt(throttleStr, 16) * 100 / 255;runTimePO.setThrottle(throttle_1);if (Util.DEBUG) {System.out.println(count++);}} else {runTimePO.setThrottle(0);}String VIN=(String) jsonObject.get("02");runTimePO.setSIN(VIN);String oilLevelStr = (String) jsonObject.get("2F");if (!oilLevelStr.contains("00")) {double oilLevel = Integer.parseInt(oilLevelStr, 16) * 100 / 255;runTimePO.setOilLevel(oilLevel);if (Util.DEBUG) {System.out.println(count++);}} else {runTimePO.setOilLevel(0);}try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Date date = new Date();String time = sdf.format(date);date = sdf.parse(time);runTimePO.setDate(date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}simpleDAO.insert();} }完成
總結
以上是生活随笔為你收集整理的struts2服务端与android交互的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 形态学图像处理(二)
- 下一篇: Android客户端与服务器之间传递js