使用Servlet返回JSON数据

通过JSON-LIB实现JSON数据的处理,涉及json-lib-2.4-jdk15.jar、commons-beanutils-1.9.3.jar、commons-collections-3.2.1.jar、commons-lang-2.5.jar、commons-logging-1.2.jar、ezmorph-1.0.6.jar包,资源包可自行下载,注意资源包的版本匹配问题;

package com.jCuckoo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@WebServlet("/ArticleServlet")
public class ArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	JSONArray jsonarray =null;
    public ArticleServlet() {
        super();
        String json="[{'id':'1','title':'我你爱中国','content':'中国123'},{'id':'2','title':'青岛好天气1','content':'111'},{'id':'2','title':'青岛好天气2','content':'2222'},{'id':'3','title':'青岛好天气3','content':'3333'},{'id':'4','title':'青岛好天气4','content':'4444'},{'id':'5','title':'青岛好天气5','content':'5555'}]";  
		jsonarray = JSONArray.fromObject(json);
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		String id=request.getParameter("id");
		if(id==null||"".equals(id)) {
			out.println(jsonarray);
			return;
		}
		for (Object object : jsonarray) {
			JSONObject o=(JSONObject)object;
			if(o.get("id").equals(id)){
				out.println(o);
				return;
			}
		}	
	}

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

}

 

你可能感兴趣的:(J2EE,微信小程序)