在已有工具类DBUtil的情况下,写一个servlet获取mysql数据库中的几组数据,形成json,传给前端
已有的DBUtil
/*
获取多个对象存入List集合
sql:传入sql语句
clazz:类信息 如Student.class
args:sql语句的参数
* */
public static <T> List<T> getList(String sql, Class<T> clazz, Object... args){
List<T> t=null;
T t2=null;
Connection conn=null;
PreparedStatement pstm=null;
ResultSet rs=null;
try {
conn=getConnection();
pstm=conn.prepareStatement(sql);
// select * from student where id=? and name=?
// 123,tom
if(args!=null){
for (int i = 0; i < args.length; i++) {
pstm.setObject((i+1),args[i]);//遍历可变数组args,循环给pstm赋参数值
}
}
rs=pstm.executeQuery();
Field[] fields=clazz.getDeclaredFields();
int index=0;
t =new ArrayList<>();
while(rs.next()){
t2=clazz.newInstance();
++index;
try {
for (int i = 0; i <fields.length ; i++) {
fields[i].setAccessible(true);//开启私有可访问
fields[i].set(t2,rs.getObject(fields[i].getName()));
fields[i].setAccessible(false);
}
t.add(t2);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return t;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
close(conn,pstm,rs);
}
return null;
}
servlet
public void getDateByNum(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
String sql ="select *from student limit ?,?";
Integer id1=Integer.parseInt(req.getParameter("num1"));
Integer id2=Integer.parseInt(req.getParameter("num2"));
System.out.println(id1+id2);
List<Student> list = new ArrayList<Student>();
list= DBUtil.getList(sql,Student.class,id1,id2);
try {
//往前端回一个json对象
resp.getWriter().println(JSONArray.parseArray(JSON.toJSONString(list)).toString());
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
前端代码
// pagestbiaostbiao.js
Page({
/**
\* 页面的初始数据
*/
data: {
listData:[]
},
login:function(e){
var that=this
wx.request({
url: 'http://localhost:8080/Manage_item_war_exploded/stu/getDateByNum?list&num1=0&num2=3',
data:{
"id":this.data.id
},success(res){
// 判断返回值是否为空
console.log(res.data)
that.setData({
alluser:false,
listData:res.data
})
}
})
},
})
<view class='container'>
<view class="tr ">
<view class="td">序号</view>
<view class="td">姓名</view>
<view class="td">性别</view>
<view class="td">班级</view>
<view class="td">电话</view>
</view>
<block wx:for="{{listData}}" wx:key="{[code]}">
<view class="tr ">
<view class="td">{{item.id}}</view>
<view class="td">{{item.name}}</view>
<view class="td">{{item.gender}}</view>
<view class="td">{{item.classes}}</view>
<view class="td">{{item.phone}}</view>
</view>
</block>
</view>