strut2服务器与android交互数据
libs如图:
web.xml:
<?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:
<?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
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:
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请求:
<%@ 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请求数据:
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框架,很多不懂,放着以后看看。有些代码参照网络的。