把从数据库中查询的记录以JSON格式返回给客户端,在这里使用gson-2.2.4.jar包。
代码结构如下:
数据库结构如下:
(1)User.java
public class User { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
(2)JdbcUtils.java
public class JdbcUtils { private static final String CLASS_NAME="com.mysql.jdbc.Driver"; private static final String URL="jdbc:mysql://localhost:3306/test"; private static final String USER="root"; private static final String PWD="mysql"; private JdbcUtils(){} static{ try{ Class.forName(CLASS_NAME); }catch(Exception e){ e.printStackTrace(); } } //建立数据库链接 public static Connection getConn()throws Exception{ return DriverManager.getConnection(URL,USER,PWD); } //释放资源 public static void free(ResultSet rs,Statement st,Connection conn){ try { if(rs!=null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ try { if(st!=null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ try { if(conn!=null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } }
(3)UserServer.java
public class UserServer { public static List<User> getUserList(){ List<User> list=null; Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; User user=null; String sql="select id,name,age from user"; try { conn=JdbcUtils.getConn(); ps=conn.prepareStatement(sql); rs=ps.executeQuery(); list=new ArrayList<User>(); while(rs.next()){ user=new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); list.add(user); } } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.free(rs, ps, conn); } return list; } }
(4)Test.java
public class Test { public static void main(String args[]){ List<User>userList=UserServer.getUserList(); if(userList!=null){ Gson gson=new Gson(); String jsonstr=gson.toJson(userList); System.out.println(jsonstr); } } }
运行结果:
[
{"id":1,"name":"zhangsan","age":23},
{"id":2,"name":"lisi","age":25},
{"id":3,"name":"王五","age":25}
]