WEB开发网
开发学院网页设计JavaScript JSON学习笔记之一 阅读

JSON学习笔记之一

 2010-09-14 13:44:03 来源:WEB开发网   
核心提示: 现在,就是在Servlet中读取对应的记录,JSON学习笔记之一(2),然后构造JSON数据,实现的Servlet为GetPermissions

现在,就是在Servlet中读取对应的记录,然后构造JSON数据,实现的Servlet为GetPermissions,如下所示:

package org.shirdrn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.xgb.bo.ManagerService;
import model.xgb.bo.impl.ManagerServiceImpl;
import model.xgb.vo.Permission;
import cn.edu.cust.levin.BusinessException;
import cn.edu.cust.levin.business.BusinessFactory;
 

/** author http://www.bt285.cn http://www.5a520.cn
*/

public class GetPermissions extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;

public GetPermissions() {
   super();
}  

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   doPost(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   request.setCharacterEncoding("utf-8");
   response.setCharacterEncoding("utf-8");
   response.setHeader("Cache-Control", "no-cache");
   response.setContentType("text/json;charset=UTF-8");
   String semester = java.net.URLDecoder.decode(request.getParameter("semester"),"UTF-8");
   int orgId = Integer.parseInt(request.getParameter("orgId"));
   PrintWriter out = response.getWriter();
   try {
    ManagerService managerService = (ManagerService)BusinessFactory
     .getBusiness(ManagerServiceImpl.class);
    List permissionList = managerService.getPermissionByOrg(orgId, semester);
    String jsonString = "[";
    for(int i=0;i<permissionList.size();i++) {
     Permission permission = (Permission)permissionList.get(i);
     jsonString += "{";
     jsonString += ""id":" + permission.getId() +",";
     jsonString += ""semester":"" + permission.getTerm() +"",";
     jsonString += ""startTime":"" + permission.getStart().toLocaleString() +"",";
     jsonString += ""endTime":"" + permission.getEndDate().toLocaleString() +"",";
     jsonString += ""orgId":" + permission.getOrg().getId() +",";
     jsonString += ""operatorId":" + permission.getOperator().getId() +",";
     jsonString += ""operatorName":"" + permission.getOperator().getName() +"",";
     jsonString += ""roleId":" + permission.getRoles().getId();
     if(i != permissionList.size()-1) {
      jsonString += "},";
     }
     else {
      jsonString += "}]";
     }
    }
    out.print(jsonString);
    out.flush();
    out.close();
   } catch (BusinessException e) {
    e.printStackTrace();
   }
}          
}

Tags:JSON 学习 笔记

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接