先看看運行的結果:html
(sql語句取的是第五條數據)java
安卓端代碼:mysql
佈局部分:item.xmlandroid
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="16dp" > <ImageView android:id="@+id/imageView1" android:layout_width="120dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:scaleType="fitXY" android:src="@drawable/timg" /> <TableLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/imageView1" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/imageView1" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名:" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="性別:" /> <TextView android:id="@+id/tv_gender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="年齡:" /> <TextView android:id="@+id/tv_age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="身高:" /> <TextView android:id="@+id/tv_hight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </TableRow> </TableLayout> </RelativeLayout>
java代碼:PersonActivity.javaweb
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.internethttp.R; import JavaBean.Person; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; public class PersonActivity extends Activity{ TextView tv_name,tv_gender,tv_age,tv_hight; String URL="http://ly-and-tl.uicp.cn:42696/AndroidServer/jsonServlet"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.item); init(); new TASK().execute(URL); } void init(){ tv_name=(TextView) findViewById(R.id.tv_name); tv_gender=(TextView) findViewById(R.id.tv_gender); tv_age=(TextView) findViewById(R.id.tv_age); tv_hight=(TextView) findViewById(R.id.tv_hight); } class TASK extends AsyncTask<String, Void, Person>{ @Override protected void onPostExecute(Person result) { // TODO Auto-generated method stub if(result!=null){ tv_name.setText(result.getName()); tv_gender.setText(result.getSex()); tv_age.setText(String.valueOf(result.getAge())); tv_hight.setText(String.valueOf(result.getHight())); } } @SuppressWarnings("finally") @Override protected Person doInBackground(String... arg0) { // TODO Auto-generated method stub Person person=null; String Url=arg0[0]; String str=null; StringBuffer sb=new StringBuffer(); try { URL url=new URL(Url); HttpURLConnection httpconn=(HttpURLConnection) url.openConnection(); httpconn.setRequestMethod("GET"); httpconn.setReadTimeout(5000); InputStream inputStream=httpconn.getInputStream(); InputStreamReader inputReader=new InputStreamReader(inputStream); BufferedReader buff=new BufferedReader(inputReader); while((str=buff.readLine())!=null){ sb.append(str); } Gson gson=new Gson(); String ss=new String(sb); System.out.println(ss); //前臺對json字符串開始轉化爲對象 person=gson.fromJson(ss, new TypeToken<Person>(){}.getType()); System.out.println(person.getName()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ return person; } } } }
安卓端的java部分的javaBean,Person.javasql
public class Person{ private String id; private String name; private String sex; private int age; private float hight; private float weight; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getHight() { return hight; } public void setHight(float hight) { this.hight = hight; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } }
接下來是服務端的代碼:數據庫
服務端的web.xml的部署:json
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>AndroidServer</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>a</servlet-name> <servlet-class>android.Internet</servlet-class> </servlet> <servlet-mapping> <servlet-name>a</servlet-name> <url-pattern>/b</url-pattern> </servlet-mapping> <servlet> <servlet-name>son</servlet-name> <servlet-class>android.JsonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>son</servlet-name> <url-pattern>/jsonServlet</url-pattern> </servlet-mapping> </web-app>
服務端的主要的頁面代碼,也就是安卓客戶端鏈接的那個頁面,JsonServlet.java後端
服務端用到了gson.jar,得把它放到tomcat的lib目錄下才能夠。tomcat
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import DataBase.DataBaseConnection; import DataBase.StudentHealthJavaBean; public class JsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 // super.doGet(req, resp); PreparedStatement prepare = null; ResultSet result = null; Connection con = null; String sql = "select * from stu_info where id=?"; StudentHealthJavaBean student=null; String str=null; con = DataBaseConnection.getConnection(); try { prepare = con.prepareStatement(sql); prepare.setString(1, "5"); result = prepare.executeQuery(); if (result != null) { student= new StudentHealthJavaBean(); if (result.next()) { student.setName(result.getString("name")); student.setAge(result.getInt("age")); student.setId(result.getString("id")); student.setSex(result.getString("sex")); student.setHight(result.getFloat("hight")); student.setWeight(result.getFloat("weight")); Gson json=new Gson(); str=json.toJson(student); //使用json包提供的轉化爲字符串 } resp.setCharacterEncoding("utf-8"); PrintWriter p = resp.getWriter(); p.println(str); //把json字符串給前臺 p.flush(); } DataBaseConnection.closeDatabaseConnection(con, prepare, result); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 super.doPost(req, resp); } }
服務端的數據庫鏈接部分代碼:
public class DataBaseConnection { public static String url1="jdbc:mysql://localhost:3306/"; public static String databaseName="students"; public static String userName="&user=root"; public static String password="&password=root"; public static String driverName="com.mysql.jdbc.Driver"; public static String encoding="&useUnicode=true&characterEncoding=UTF-8"; public static String url=url1+databaseName+"?"+"useSSL=false"+encoding+userName+password; @SuppressWarnings("finally") public static Connection getConnection() { Connection con=null; try { Class.forName(driverName); con=DriverManager.getConnection(url); } catch (ClassNotFoundException | SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally { return con; } } public static void closeDatabaseConnection(Connection con,PreparedStatement ps,ResultSet rs) { try { if(rs!=null)rs.close(); if(ps!=null) ps.close(); if(con!=null) con.close(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } }
服務端的javabean和安卓端的同樣,字段名和數據庫如出一轍就OK
public class StudentHealthJavaBean { private String id; private String name; private String sex; private int age; private float hight; private float weight; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getHight() { return hight; } public void setHight(float hight) { this.hight = hight; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public StudentHealthJavaBean() { // TODO 自動生成的構造函數存根 } }