设有一个业务查询页面,查询的数据是一个组织或企业的部门组成信息表Department(对应的是Department类),含有以下信息:部门id、部门编号、部门名称、部门负责人、部门编制(人数)、部门职责等信息,查询页面需要服务器提供JSON格式的数据
时间: 2024-02-07 11:04:07 浏览: 104
02_查询中使用JSON数据格式
好的,以下是对应的Java代码:
```java
public class Department {
private int id;
private String number;
private String name;
private String leader;
private int personnel;
private String duty;
public Department(int id, String number, String name, String leader, int personnel, String duty) {
this.id = id;
this.number = number;
this.name = name;
this.leader = leader;
this.personnel = personnel;
this.duty = duty;
}
// getter and setter methods
}
// 在ServletDepartment类中处理请求
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 查询Department信息并封装为List<Department>
List<Department> departmentList = queryDepartmentInfo();
// 将List<Department>转为JSON格式数据
JSONArray jsonArray = new JSONArray();
for (Department department : departmentList) {
JSONObject json = new JSONObject();
json.put("id", department.getId());
json.put("number", department.getNumber());
json.put("name", department.getName());
json.put("leader", department.getLeader());
json.put("personnel", department.getPersonnel());
json.put("duty", department.getDuty());
jsonArray.add(json);
}
String json = jsonArray.toJSONString();
// 设置响应头
response.setContentType("application/json;charset=UTF-8");
// 返回JSON格式数据
PrintWriter out = response.getWriter();
out.write(json);
out.flush();
out.close();
}
```
您可以使用浏览器或Postman等工具模拟请求并测试返回结果。希望对您有所帮助。
阅读全文