Android手机客户端通过JSP实现与Tomcat服务器端通信(Msql数据库,Json作为载体)
--服务端代码
服务器端主要代码:
1.首先构建一个Person类,用来保存用户信息
[java]viewplaincopy
publicclassPerson
privateStringname;
privateStringaddress;
privateIntegerage;
publicPerson(){
super();
}
publicPerson(Stringname,Stringaddress,Integerage){
super();
this.name=name;
this.address=address;
this.age=age;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
publicIntegergetAge(){
returnage;
}
publicvoidsetAge(Integerage){
this.age=age;
}
}
2.服务器端的service类
[java]viewplaincopy
importjava.io.PrintWriter;
importjava.sql.*;
importjava.util.*;
publicclassJsonService{
publicstaticList<Person>getListPerson(){
Stringa,b,allString="";
intc=0;
List<Person>mLists=newArrayList<Person>();
//List<Person>mLists=newArrayList<Person>();
//mLists.add(newPerson("临风","北京",20));
System.out.println(mLists);
try{
Class.forName("com.mysql.jdbc.Driver");//链接数据库
Connectionconn=DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/json","root","123456");
Statementstmt=conn.createStatement();
ResultSetrs=stmt.executeQuery("select*frompeople");//遍历数据库
Personp=null;
while(rs.next())
{
System.out.println(rs.getString(1)+"\t"
+rs.getString(2)+"\t"
+rs.getInt(3));
a=rs.getString(1);
b=rs.getString(2);
c=rs.getInt(3);
mLists.add(newPerson(a,b,c));//添加到List中
}
System.out.println(mLists);
}catch(Exceptione){
System.out.println(e);
e.printStackTrace();
returnmLists;
}
//finally{
//returnmLists;
//}
System.out.println(mLists);
returnmLists;
}
//测试用主函数
publicstaticvoidmain(String[]args)throwsException
{
Stringstr[]=null;
JsonServicecon=newJsonService();
List<Person>temp=con.getListPerson();
//System.out.println(temp.);
//str=temp.split("");
//for(inti=0;i<str.length;i++){
//System.out.println(str[i]);
//}
//System.out.println(str.length);
}
}
3.服务器端servlet类,接受android端的请求,并且将List中的Person数据转换为Json的格式,实现Json的数据传输
[java]viewplaincopy
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.jiangqq.bean.Person;
importcom.jiangqq.csdn.JsonService;
publicclassJsonServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
try{
PrintWriterout=response.getWriter();
List<Person>persons=JsonService.getListPerson();//返回JsonService的数据
StringBuffersb=newStringBuffer();//数据缓存
sb.append('[');
for(Personperson:persons){//person.getName(),person.getAddress()获得姓名,地址,一些符号转换为char
//锁定输出=>{"name":"姓名","address":"地址","age":年龄},
sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(",");
sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
sb.append("\"age\":").append(person.getAge());
sb.append('}').append(",");
}
sb.deleteCharAt(sb.length()-1);
sb.append(']');
out.write(newString(sb));
out.flush();
out.close();//关闭
}catch(Exceptione){
System.out.println(e);
e.printStackTrace();
}
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doGet(request,response);
}
}
环境搭建:
1.在Tomcat7.0\webapps\JsonWeb\WEB-INF\lib目录中加入了mysql-connector-java-5.0.8-bin.jar以及servlet-api.jar
2.然后在主目Tomcat7.0\webapps\JsonWeb录的index.jsp中加入引用包的代码
[java]viewplaincopy
<%@pageimport="java.util.*"%>
<%@pageimport="java.sql.*"%>
结果测试:在浏览器输入http://localhost:8080/JsonWeb/JsonServlet,返回格式化好的json数据
--客户端代码
1.客户端文件,JsonParse,Json文件解析
[java]viewplaincopy
importjava.io.ByteArrayOutputStream;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.nio.charset.Charset;
importjava.util.ArrayList;
importjava.util.List;
importorg.json.JSONArray;
importorg.json.JSONObject;
importcom.jiangqq.bean.Person;
publicclassJsonParse{
/**
*解析Json数据
*
*@paramurlPath
*@returnmlists
*@throwsException
*/
publicstaticList<Person>getListPerson(StringurlPath)throwsException{
List<Person>mlists=newArrayList<Person>();
byte[]data=readParse(urlPath);
JSONArrayarray=newJSONArray(newString(data));
for(inti=0;i<array.length();i++){
JSONObjectitem=array.getJSONObject(i);
Stringname=item.getString("name");
Stringaddress=item.getString("address");
intage=item.getInt("age");
mlists.add(newPerson(name,address,age));
}
returnmlists;
}
/**
*从指定的url中获取字节数组
*
*@paramurlPath
*@return字节数组
*@throwsException
*/
publicstaticbyte[]readParse(StringurlPath)throwsException{
ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
byte[]data=newbyte[1024];
intlen=0;
URLurl=newURL(urlPath);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
InputStreaminStream=conn.getInputStream();
while((len=inStream.read(data))!=-1){
outStream.write(data,0,len);
}
inStream.close();
returnoutStream.toByteArray();
}
}
2.客户端主要类,MainActivity,发送请求
[java]viewplaincopy
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importcom.jiangqq.bean.Person;
importcom.jiangqq.util.JsonParse;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
privateButtonmButton;
privateListViewmListView;
privatestaticfinalStringurlPath="http://192.168.1.100:8080/JsonWeb/JsonServlet";
privatestaticfinalStringTAG="MainActivity";
privateList<Person>persons;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton=(Button)findViewById(R.id.button1);
mListView=(ListView)findViewById(R.id.listView1);
mButton.setOnClickListener(newMyOnClickListener());
}
privateclassMyOnClickListenerimplementsOnClickListener{
@Override
publicvoidonClick(Viewv){
try{
//得到Json解析成功之后数据
persons=JsonParse.getListPerson(urlPath);
List<HashMap<String,Object>>data=newArrayList<HashMap<String,Object>>();
for(inti=0;i<persons.size();i++){
HashMap<String,Object>map=newHashMap<String,Object>();
map.put("name",persons.get(i).getName());
map.put("address",persons.get(i).getAddress());
map.put("age",persons.get(i).getAge());
data.add(map);
}
SimpleAdapter_Adapter=newSimpleAdapter(MainActivity.this,
data,R.layout.listview_item,newString[]{"name",
"address","age"},newint[]{R.id.textView1,
R.id.textView2,R.id.textView3});
mListView.setAdapter(_Adapter);
}catch(Exceptione){
Toast.makeText(MainActivity.this,"解析失败",2000);//在手机上显示提示Toast,2秒
Log.i(TAG,e.toString());//DDMS中显示提示
}
}
}
}
3.同上一篇的,Person构造的数据类
[java]viewplaincopy
packagecom.jiangqq.bean;
publicclassPerson{
privateStringname;
privateStringaddress;
privateIntegerage;
publicPerson(){
super();
}
publicPerson(Stringname,Stringaddress,Integerage){
super();
this.name=name;
this.address=address;
this.age=age;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
publicIntegergetAge(){
returnage;
}
publicvoidsetAge(Integerage){
this.age=age;
}
@Override
publicStringtoString(){
return"Person[name="+name+",address="+address+",age="+age
+"]";
}
}
4.AndroidManifest.xml别忘记添加
[java]viewplaincopy
<uses-permissionandroid:name="android.permission.INTERNET"/>
[java]viewplaincopy
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.jiangqq.csdn"
android:versionCode="1"
android:versionname="1.0">
<uses-sdkandroid:minSdkVersion="8"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permissionandroid:name="android.permission.INTERNET"/>
</manifest>