Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> strut2服務器與android交互數據

strut2服務器與android交互數據

編輯:關於Android編程

libs如圖:

 

web.xml:


[html] 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="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"> 
    <!-- 定義Struts2的核心控制器:FilterDispatcher --> 
    <filter> 
        <!-- 定義核心Filter的名稱 --> 
        <filter-name>struts2</filter-name> 
        <!-- 定義Filter的實現類 --> 
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 
    </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>  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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">
 <!-- 定義Struts2的核心控制器:FilterDispatcher -->
 <filter>
  <!-- 定義核心Filter的名稱 -->
  <filter-name>struts2</filter-name>
  <!-- 定義Filter的實現類 -->
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
 </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>


struts.xml:


[html]
<?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> 
    <constant name="struts.i18n.encoding" value="utf-8"></constant> 
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> 
    <package name="default" extends="json-default" namespace="/"> 
        <action name="getjson" class="com.zte.android.LoginAction" 
            method="login"> 
            <result type="json"></result> 
        </action> 
    </package> 
</struts> 

<?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>
 <constant name="struts.i18n.encoding" value="utf-8"></constant>
 <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
 <package name="default" extends="json-default" namespace="/">
  <action name="getjson" class="com.zte.android.LoginAction"
   method="login">
   <result type="json"></result>
  </action>
 </package>
</struts>


Student.java


[html] 
package com.zte.android; 
 
public class Student 

 
    private String name; 
 
    private String age; 
 
    private String school; 
 
    private String phone; 
 
    public String getName() 
    { 
        return name; 
    } 
 
    public void setName(String name) 
    { 
        this.name = name; 
    } 
 
    public String getAge() 
    { 
        return age; 
    } 
 
    public void setAge(String age) 
    { 
        this.age = age; 
    } 
 
    public String getSchool() 
    { 
        return school; 
    } 
 
    public void setSchool(String school) 
    { 
        this.school = school; 
    } 
 
    public String getPhone() 
    { 
        return phone; 
    } 
 
    public void setPhone(String phone) 
    { 
        this.phone = phone; 
    } 
 

package com.zte.android;

public class Student
{

 private String name;

 private String age;

 private String school;

 private String phone;

 public String getName()
 {
  return name;
 }

 public void setName(String name)
 {
  this.name = name;
 }

 public String getAge()
 {
  return age;
 }

 public void setAge(String age)
 {
  this.age = age;
 }

 public String getSchool()
 {
  return school;
 }

 public void setSchool(String school)
 {
  this.school = school;
 }

 public String getPhone()
 {
  return phone;
 }

 public void setPhone(String phone)
 {
  this.phone = phone;
 }

}

Login.action:


[html] 
package com.zte.android; 
 
import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 
import java.util.List; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.struts2.interceptor.ServletRequestAware; 
import org.apache.struts2.interceptor.ServletResponseAware; 
import com.google.gson.Gson; 
import com.opensymphony.xwork2.ActionSupport; 
 
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() 
    { 
        returnUserInfo(); 
    } 
 
    private void returnUserInfo() 
    { 
 
        this.response.setContentType("text/json;charset=utf-8"); 
        this.response.setCharacterEncoding("UTF-8"); 
        String json; 
        if (username == null || password == null) 
        { 
 
            json = "請求參數錯誤"; 
            flushData(json); 
            return; 
        } 
        if (username.equals("123") && password.equals("123")) 
        { 
            List<Student> list = new ArrayList<Student>(); 
            Gson gson = new Gson(); 
            for (int i = 0; i < 10; i++) 
            { 
                Student st = new Student(); 
                st.setAge("10" + i); 
                st.setName("csh" + i); 
                st.setPhone("1333007" + i); 
                st.setSchool("abc" + i); 
                list.add(st); 
            } 
            json = gson.toJson(list); 
        } 
        else 
        { 
            json = "非法登陸信息!"; 
        } 
        flushData(json); 
    } 
 
    private void flushData(String json) 
    { 
        byte[] jsonBytes; 
        try 
        { 
            jsonBytes = json.getBytes("utf-8"); 
            response.setContentLength(jsonBytes.length); 
            response.getOutputStream().write(jsonBytes); 
            response.getOutputStream().flush(); 
        } 
        catch (UnsupportedEncodingException e) 
        { 
            e.printStackTrace(); 
        } 
        catch (IOException e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            try 
            { 
                response.getOutputStream().close(); 
            } 
            catch (IOException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
 
    } 

package com.zte.android;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

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()
 {
  returnUserInfo();
 }

 private void returnUserInfo()
 {

  this.response.setContentType("text/json;charset=utf-8");
  this.response.setCharacterEncoding("UTF-8");
  String json;
  if (username == null || password == null)
  {

   json = "請求參數錯誤";
   flushData(json);
   return;
  }
  if (username.equals("123") && password.equals("123"))
  {
   List<Student> list = new ArrayList<Student>();
   Gson gson = new Gson();
   for (int i = 0; i < 10; i++)
   {
    Student st = new Student();
    st.setAge("10" + i);
    st.setName("csh" + i);
    st.setPhone("1333007" + i);
    st.setSchool("abc" + i);
    list.add(st);
   }
   json = gson.toJson(list);
  }
  else
  {
   json = "非法登陸信息!";
  }
  flushData(json);
 }

 private void flushData(String json)
 {
  byte[] jsonBytes;
  try
  {
   jsonBytes = json.getBytes("utf-8");
   response.setContentLength(jsonBytes.length);
   response.getOutputStream().write(jsonBytes);
   response.getOutputStream().flush();
  }
  catch (UnsupportedEncodingException e)
  {
   e.printStackTrace();
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
  finally
  {
   try
   {
    response.getOutputStream().close();
   }
   catch (IOException e)
   {
    e.printStackTrace();
   }
  }

 }
}
網頁ajax請求:


[html] 
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
    String path = request.getContextPath(); 
    String basePath = request.getScheme() + "://" 
            + request.getServerName() + ":" + request.getServerPort() 
            + path + "/"; 
%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 
 
<title>My JSP 'index.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    --> 
</head> 
<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浏覽器支持的創建方式   
        } 
    } 
    function loadAjax() { 
        createXmlHttp(); //創建XmlHttpRequest對象   
        var url = "http://localhost:8080/ssh2ToAndroid/getjson.action?userName=admin&password=123456"; 
        xmlHttpReq.open("GET", url, true); 
        xmlHttpReq.onreadystatechange = loadCallback; //IE這裡設置回調函數   
        xmlHttpReq.send(null); 
    } 
    function loadCallback() { 
        alert(xmlHttpReq.readyState); 
        if (xmlHttpReq.readyState == 4) { 
            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> 
</html> 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
</head>
<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浏覽器支持的創建方式 
  }
 }
 function loadAjax() {
  createXmlHttp(); //創建XmlHttpRequest對象 
  var url = "http://localhost:8080/ssh2ToAndroid/getjson.action?userName=admin&password=123456";
  xmlHttpReq.open("GET", url, true);
  xmlHttpReq.onreadystatechange = loadCallback; //IE這裡設置回調函數 
  xmlHttpReq.send(null);
 }
 function loadCallback() {
  alert(xmlHttpReq.readyState);
  if (xmlHttpReq.readyState == 4) {
   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>
</html>

android請求數據:


[html] 
package com.zte.android.greenweb.launcher.http; 
 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.URL; 
 
import com.zte.android.greenweb.launcher.util.LogEx; 
import com.zte.android.greenweb.launcher.util.NetConst; 
 
public class HttpConnectionClient 

 
    public static final String HTTP_REQUEST_METHOD_GET = "GET"; 
 
    public static final String HTTP_REQUEST_METHOD_POST = "POST"; 
 
    private HttpURLConnection conn = null; 
 
    /** 
     * 發送請求到http服務然後接收返回報文 
     *  
     * @param path 
     *            請求的http服務的路徑 
     * @return 返回請求的響應信息 
     * @throws IOException 
     */ 
    public int doGet(String path) throws IOException 
    { 
        URL url = new URL(path); 
        // openConnection() 返回一個 URLConnection 對象,它表示到 URL 所引用的遠程對象的連接 
        conn = (HttpURLConnection) url.openConnection();// 打開一個連接 
        conn.setRequestMethod(HTTP_REQUEST_METHOD_GET);// 設置get方式請求 
        conn.setConnectTimeout(NetConst.CONNECTED_TIME_OUT); 
        conn.setReadTimeout(NetConst.READ_TIME_OUT); 
        // 打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true 
        conn.setDoOutput(true); 
        // 這裡只設置內容類型與內容長度的頭字段根據傳送內容決定 
        // 內容類型Content-Type: 
        // application/x-www-form-urlencoded、text/xml;charset=GBK 
        // 內容長度Content-Length: 38 
        conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); 
        conn.setRequestProperty("Charset", "UTF-8"); 
        // 保存調用http服務後的響應信息 
        return conn.getResponseCode(); 
    } 
 
    /** 
     * 發送請求到http服務然後接收返回報文 
     *  
     * @param jsonStr 
     *            請求的json格式的字符串 
     * @param path 
     *            請求的http服務的路徑 
     * @return 返回請求的響應信息 
     * @throws IOException 
     */ 
    public int doPost(String jsonStr, String path) throws IOException 
    { 
        LogEx.d("doPost request="+jsonStr); 
        // 得到請求報文的二進制數據 
        byte[] data = jsonStr.getBytes(); 
        URL url = new URL(path); 
        // 打開一個連接 
        conn = (HttpURLConnection) url.openConnection(); 
        // 設置post方式請求 
        conn.setRequestMethod(HTTP_REQUEST_METHOD_POST); 
        conn.setConnectTimeout(NetConst.CONNECTED_TIME_OUT); 
        conn.setReadTimeout(NetConst.READ_TIME_OUT); 
        // 打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true 
        conn.setDoOutput(true); 
        conn.setDoInput(true); 
        // 這裡只設置內容類型與內容長度的頭字段根據傳送內容決定 
        // 內容類型Content-Type: 
        // application/x-www-form-urlencoded、text/xml;charset=GBK 
        // 內容長度Content-Length: 38 
        conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); 
        conn.setRequestProperty("Charset", "UTF-8"); 
        conn.setRequestProperty("Content-Length", String.valueOf(data.length)); 
        OutputStream outStream = conn.getOutputStream();// 返回寫入到此連接的輸出流 
        // 把二進制數據寫入是輸出流 
        outStream.write(data); 
        // 內存中的數據刷入 
        outStream.flush(); 
        // 關閉流 
        outStream.close(); 
        int ic = 0; 
        ic = conn.getResponseCode(); 
        return ic; 
    } 
 
    public String getContent() throws UnsupportedEncodingException, IOException 
    { 
        if (null == conn) 
        { 
            return null; 
        } 
 
        // 保存調用http服務後的響應信息 
        String msg = ""; 
        // 如果請求響應碼是200,則表示成功 
        if (conn.getResponseCode() == NetConst.NET_CONNECTED_SUCCESS) 
        { 
            // HTTP服務端返回的編碼是UTF-8,故必須設置為UTF-8,保持編碼統一,否則會出現中文亂碼 
            BufferedReader in = 
                    new BufferedReader(new InputStreamReader( 
                            (InputStream) conn.getInputStream(), "UTF-8"));// 返回從此打開的連接讀取的輸入流 
            msg = in.readLine(); 
            in.close(); 
        } 
        // 斷開連接 
        conn.disconnect(); 
        LogEx.d("doPost getContent="+msg); 
        return msg; 
    } 

package com.zte.android.greenweb.launcher.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.zte.android.greenweb.launcher.util.LogEx;
import com.zte.android.greenweb.launcher.util.NetConst;

public class HttpConnectionClient
{

 public static final String HTTP_REQUEST_METHOD_GET = "GET";

 public static final String HTTP_REQUEST_METHOD_POST = "POST";

 private HttpURLConnection conn = null;

 /**
  * 發送請求到http服務然後接收返回報文
  *
  * @param path
  *            請求的http服務的路徑
  * @return 返回請求的響應信息
  * @throws IOException
  */
 public int doGet(String path) throws IOException
 {
  URL url = new URL(path);
  // openConnection() 返回一個 URLConnection 對象,它表示到 URL 所引用的遠程對象的連接
  conn = (HttpURLConnection) url.openConnection();// 打開一個連接
  conn.setRequestMethod(HTTP_REQUEST_METHOD_GET);// 設置get方式請求
  conn.setConnectTimeout(NetConst.CONNECTED_TIME_OUT);
  conn.setReadTimeout(NetConst.READ_TIME_OUT);
  // 打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true
  conn.setDoOutput(true);
  // 這裡只設置內容類型與內容長度的頭字段根據傳送內容決定
  // 內容類型Content-Type:
  // application/x-www-form-urlencoded、text/xml;charset=GBK
  // 內容長度Content-Length: 38
  conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
  conn.setRequestProperty("Charset", "UTF-8");
  // 保存調用http服務後的響應信息
  return conn.getResponseCode();
 }

 /**
  * 發送請求到http服務然後接收返回報文
  *
  * @param jsonStr
  *            請求的json格式的字符串
  * @param path
  *            請求的http服務的路徑
  * @return 返回請求的響應信息
  * @throws IOException
  */
 public int doPost(String jsonStr, String path) throws IOException
 {
  LogEx.d("doPost request="+jsonStr);
  // 得到請求報文的二進制數據
  byte[] data = jsonStr.getBytes();
  URL url = new URL(path);
  // 打開一個連接
  conn = (HttpURLConnection) url.openConnection();
  // 設置post方式請求
  conn.setRequestMethod(HTTP_REQUEST_METHOD_POST);
  conn.setConnectTimeout(NetConst.CONNECTED_TIME_OUT);
  conn.setReadTimeout(NetConst.READ_TIME_OUT);
  // 打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true
  conn.setDoOutput(true);
  conn.setDoInput(true);
  // 這裡只設置內容類型與內容長度的頭字段根據傳送內容決定
  // 內容類型Content-Type:
  // application/x-www-form-urlencoded、text/xml;charset=GBK
  // 內容長度Content-Length: 38
  conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
  conn.setRequestProperty("Charset", "UTF-8");
  conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  OutputStream outStream = conn.getOutputStream();// 返回寫入到此連接的輸出流
  // 把二進制數據寫入是輸出流
  outStream.write(data);
  // 內存中的數據刷入
  outStream.flush();
  // 關閉流
  outStream.close();
  int ic = 0;
  ic = conn.getResponseCode();
  return ic;
 }

 public String getContent() throws UnsupportedEncodingException, IOException
 {
  if (null == conn)
  {
   return null;
  }

  // 保存調用http服務後的響應信息
  String msg = "";
  // 如果請求響應碼是200,則表示成功
  if (conn.getResponseCode() == NetConst.NET_CONNECTED_SUCCESS)
  {
   // HTTP服務端返回的編碼是UTF-8,故必須設置為UTF-8,保持編碼統一,否則會出現中文亂碼
   BufferedReader in =
     new BufferedReader(new InputStreamReader(
       (InputStream) conn.getInputStream(), "UTF-8"));// 返回從此打開的連接讀取的輸入流
   msg = in.readLine();
   in.close();
  }
  // 斷開連接
  conn.disconnect();
  LogEx.d("doPost getContent="+msg);
  return msg;
 }
}

最近在學ssh2框架,很多不懂,放著以後看看。有些代碼參照網絡的。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved