Servlet端doPost()方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); // response.setContentType("text/xml;charset=utf-8"); String format = request.getParameter("format");// 获取url传过来的数据 ResultSet rs = userinfo.queryUserInfo("1=1"); XmlJsonInter xmlJson = new XmlJsonImpl(); if ("json".equals(format)) { xmlJson.JSON(rs, request, response); } else { xmlJson.XML(rs, request, response); // PrintWriter out=response.getWriter(); // out.write("ceshi"); } }
JSON方法和XML方法的实现:
package net.palm_on_campus.dao.interImpl; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.jstl.core.Config; import net.palm_on_campus.dao.inter.XmlJsonInter; import net.palm_on_campus.dao.model.UserInfo; /** * <p>================MyEclipse=================== * <p>将数据库中查询得到的数据转换为xml或者json格式[接口的实现] * <p>2013-7-22上午10:35:33 * <p>============================================ * @author YI */ public class XmlJsonImpl implements XmlJsonInter { @Override public void JSON(ResultSet rs, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // json格式: [{id:56,title:"xxxx",timelength:90}] StringBuilder builder = new StringBuilder(); builder.append('['); try { if (rs != null) while (rs.next()) { builder.append('{'); builder.append("username:") .append(rs.getString("username")).append(','); builder.append("userlogin:\"") .append(rs.getString("userlogin")).append("\","); builder.append("userpwd:\"") .append(rs.getString("userpwd")).append("\","); builder.append("flag:\"") .append(rs.getString("flag")).append("\","); builder.append("note:").append(rs.getString("note")); builder.append("},"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } builder.deleteCharAt(builder.length() - 1); builder.append(']'); request.setAttribute("json",builder.toString()); request.getRequestDispatcher("/json.jsp").forward(request, response); } @Override public void XML(ResultSet rs, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<UserInfo> users = new ArrayList<UserInfo>(); try { while (rs.next()) { UserInfo user = new UserInfo(); user.setUserName(rs.getString("username")); user.setUserPwd(rs.getString("userpwd")); user.setUserLogin(rs.getString("userlogin")); user.setNote(rs.getString("note")); user.setFlag(Integer.parseInt(rs.getString("flag"))); users.add(user); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("users", users); request.getRequestDispatcher("/xml.jsp").forward(request, response); } }
json.jsp,和xml.jsp的实现:
json.jsp:
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
xml.jsp
<?xml version="1.0" encoding="utf-8"?> <!--上面这句话必须为第一句,否则pull解析器报错 --> <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <userinfo> <c:forEach items="${users}" var="user"> <user> <username>${user.userName}</username> <userlogin>${user.userLogin}</userlogin> <note>${user.note}</note> <userpwd>${user.userPwd}</userpwd> <flag>${user.flag}</flag> </user> </c:forEach> </userinfo>
WEB端测试[test.jsp]:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> </head> <body> <form action="UserInfoServlet" method="post"> 用户名:<input name="bookname" type="text"/> <p/> <input type="submit" value="查询"/> </form> </body> </html>
测试结果数据显示为:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
ANDROID端:
Tools工具类:[请根据需要改写,以下是解析json,和xml数据方法------仅供参考]
Tools.class:
package net.palm_on_campus.tools; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.palm_on_campus.model.Info; import net.palm_on_campus.model.UserInfo; import org.json.JSONArray; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; public class Tools { public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while( (inStream.read(buffer)) !=-1){ outputStream.write(buffer); } inStream.close(); return outputStream.toByteArray(); } /** * ------------------------------ * <p>解析json数据 * @param is 输入流 * @return * @throws Exception * 2013-7-22 * @----------------------------- */ public static List<Info> parseJSON(InputStream is) throws Exception { List<Info> arruser = new ArrayList<Info>(); byte[] data =Tools.read(is); //将字节数组转换成字符串 String json= new String(data); //将json对象转换成json的数组对象 JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject=array.getJSONObject(i); Info userInfo=new UserInfo(jsonObject); // userInfo.setUserName(jsonObject.getString("username")); // userInfo.setUserLogin(jsonObject.getString("userlogin")); // userInfo.setNote(jsonObject.getString("note")); // userInfo.setFlag(Integer.parseInt(jsonObject.getString("flag"))); // userInfo.setUserPwd(jsonObject.getString("userpwd")); arruser.add(userInfo); } return arruser; } /** * ------------------------------ * <p>解析xml数据 * @param is * @return * @throws Exception * 2013-7-22 * @----------------------------- */ public static List<Info> parseXML(InputStream is) throws Exception{ List<Info> users=null; UserInfo user = null; //用Pull解析器解析XML文件 XmlPullParser parser= Xml.newPullParser(); parser.setInput(is, "UTF-8"); int event = parser.getEventType(); //不等于结束事件,循环读取XML文件并封装成对象 while(event !=XmlPullParser.END_DOCUMENT){ switch (event) { case XmlPullParser.START_DOCUMENT: users= new ArrayList<Info>(); break; case XmlPullParser.START_TAG: if("username".equals(parser.getName())){ user.setUserName(parser.nextText()); }else if("userlogin".equals(parser.getName())){ user.setUserLogin(parser.nextText()); }else if("userpwd".equals(parser.getName())){ user.setUserPwd(parser.nextText()); }else if("note".equals(parser.getName())){ user.setNote(parser.nextText()); }else if("flag".equals(parser.getName())){ user.setFlag(Integer.parseInt(parser.nextText())); }else if("user".equals(parser.getName())){ user=new UserInfo(); } break; case XmlPullParser.END_TAG: if("user".equals(parser.getName())){ users.add(user); user = null; } break; } event = parser.next(); } return users; } }
以上涉及的Info.class和UserInfo.class
package net.palm_on_campus.model; /** * <p>=================Eclipse==================== * <p>这个类名义上是所有信息的父类,但并没有储存信息。只是为了实现多态,从而达到统一接口命名 * <p>之所以要统一命名是为了使得Tools类中parseJSON,parseXML等方法的通用性 * <p>但是又不能直接去定义接口,因为接口的实现要实现接口中所有方法,但是时间使用中不一定全部需要 * <p>2013-7-23下午12:46:35 * <p>============================================ * @author YI */ public abstract class Info { //begin---------以下抽象方法为UserInfo实现的方法进行注册------------ public abstract int getFlag(); public abstract void setFlag(int flag); public abstract String getUserLogin(); public abstract void setUserLogin(String userLogin); public abstract String getUserName(); public abstract void setUserName(String userName); public abstract String getUserPwd(); public abstract void setUserPwd(String userPwd); public abstract String getNote(); public abstract void setNote(String note); //end------------------------------------------------------------- }
package net.palm_on_campus.model; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; /** * <p>=================Eclipse==================== * <p>用户信息原型 * <p>2013-7-21下午4:56:19 * <p>============================================ * @author YI */ public class UserInfo extends Info{ private String userLogin;//用户登陆名 private String userName;//用户名 private String userPwd;//用户密码 private String note;//用户备注信息 private int flag;//标志 public UserInfo(){} /** * @param userlogin 登陆名 * @param username 用户名 * @param userpwd 密码 * @param note 备注 * @param flag 标志 */ public UserInfo(String userlogin,String username,String userpwd,String note,int flag){ this.userLogin=userlogin; this.userName=username; this.userPwd=userpwd; this.note=note; this.flag=flag; } /** * 通过HashMap对用户进行初始化 * @param map */ public UserInfo(HashMap<String, Object> map){ this.userName=map.get("username").toString(); this.userLogin=map.get("userlogin").toString(); this.userPwd=map.get("userpwd").toString(); this.note=map.get("note").toString(); this.flag=Integer.parseInt(map.get("username").toString()); } /** * 解析JSONObject数据对用户初始化 * @param jsonObject 一组JSONArray对象中一个JSONObject * @throws JSONException */ public UserInfo(JSONObject jsonObject) throws JSONException{ this.userLogin = jsonObject.getString("userlogin"); this.userName = jsonObject.getString("username"); this.userPwd = jsonObject.getString("userpwd"); this.note = jsonObject.getString("note"); this.flag = Integer.parseInt(jsonObject.getString("flag")); } public String getUserLogin() { return userLogin; } public void setUserLogin(String userLogin) { this.userLogin = userLogin; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } }
[备注,使用者可以不要使用Info类,笔者我是由于一些需要,没有用Info类,只需要把Info-〉UserInfo]
向服务器接收信息的链接服务类:
package net.palm_on_campus.service; import java.io.InputStream; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Xml; import net.palm_on_campus.config.ShlConfig; import net.palm_on_campus.model.Info; import net.palm_on_campus.model.UserInfo; import net.palm_on_campus.tools.Tools; /** * <p>=================Eclipse==================== * <p>程序服务类 * <p>JSON,XML数据加工 * <p>2013-7-21下午4:58:10 * <p>============================================ * @author YI */ public class CampusService implements ShlConfig{ /** * ------------------------------ * @param PATH 请求服务地址 * @return * @throws Exception * 2013-7-22 * @----------------------------- */ public static List<Info> getHTTPData(String PATH) throws Exception{ URL url = new URL(PATH); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setRequestMethod("GET"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); if(PATH.indexOf("format=json")!=-1) return Tools.parseJSON(inStream); else return Tools.parseXML(inStream); } return null; } }
Activity:
package net.palm_on_campus.campus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.palm_on_campus.config.ShlConfig; import net.palm_on_campus.model.Info; import net.palm_on_campus.model.UserInfo; import net.palm_on_campus.service.CampusService; import com.palm_on_campus.campus.R; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; /** * <p>=================Eclipse==================== * <p>MainActivity程序的入口 * <p>2013-7-21下午4:52:29 * <p>============================================ * @author YI */ public class MainActivity extends Activity implements ShlConfig{ /** Called when the activity is first created. */ public static MainActivity app; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app=this; ListView listView=(ListView)findViewById(R.id.listView1); try { List<Info> userinfo =CampusService.getHTTPData(SER_URL+"?format=json"); //List<UserInfo> userinfo =CampusService.getJSONData(); List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>(); for(Info user:userinfo){ HashMap<String, Object> map=new HashMap<String, Object>(); map.put("username", user.getUserName()); map.put("userlogin", user.getUserLogin()); map.put("note", user.getNote()); map.put("pwd", "*********"/*user.getUserPwd()*/); map.put("flag", user.getFlag()); data.add(map); } SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[]{"username","userlogin","note","pwd","flag"}, new int[]{R.id.tv1,R.id.tv2,R.id.tv3,R.id.tv4,R.id.tv5}); listView.setAdapter(adapter); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[SER_URL定义在接口中,可直接改为地址]
package net.palm_on_campus.config; /** * <p>=================Eclipse==================== * <p>配置文件定义为接口 * <p>2013-7-21下午4:53:42 * <p>============================================ * @author YI */ public interface ShlConfig { /** * 服务器地址 */ final String SER_URL="http://192.168.1.44:8080/campus1_1/UserInfoServlet"; }
有问题可以e-mail我:[email protected]
[初学,还请多多指教]