Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > jsp技巧

Java_Servlet生成JSON格式数据并用jQuery显示的方法

来源:中文源码网    浏览:141 次    日期:2024-05-17 02:13:18
【下载文档:  Java_Servlet生成JSON格式数据并用jQuery显示的方法.txt 】


Java Servlet生成JSON格式数据并用jQuery显示的方法
本文实例讲述了Java Servlet生成JSON格式数据并用jQuery显示的方法。分享给大家供大家参考,具体如下:
1、Servlet通过json-lib生成JSON格式的数据
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
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 json.Person;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@WebServlet("/JSONServlet")
public class JSONServlet extends HttpServlet {
public JSONServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/x-json");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
ArrayList items=new ArrayList();
items.add(new Person(2,"jack"));
items.add(new Person(2,"bob"));
items.add(new Person(2,"alex"));
JSONArray jsonArray=new JSONArray();
jsonArray.addAll(items);
out.print(jsonArray.toString());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
// Put your code here
}
}
2、前端页面代码
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">



Insert title here








jQuery也可以用.getJSON实现异步数据获取

希望本文所述对大家JSP程序设计有所帮助。

相关内容