将JSONObject传递给JSP并打印数据

时间:2013-03-18 09:37:58

标签: json jsp

在servlet中创建一个JSONObject并将该对象传递给JSP。

JSONObject jo=new JSONObject();
jo.put("site","java4s.com");
jo.put("content","Java");
jo.put("TotalLinks",927);
HttpSession session=request.getSession(true);
session.setAttribute("jsonObject", jo);
RequestDispatcher rd = request.getRequestDispatcher("viewpage.jsp");
rd.forward(request, response);

这是我的JSP页面

<%@page import="com.google.gson.JsonObject"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Json</title>
<%
JSONObject jsonObject=(JSONObject)session.getAttribute("jsonObject");
%>

</head>
<body>
<h6>JSON View</h6>
<br>
<%=jsonObject%>
</body>
</html>

但JSP页面显示 JSONObject 无法解析为类型的错误。但我已经添加了jar文件,并且在Servlet中它没有显示错误。我该怎么办?感谢

1 个答案:

答案 0 :(得分:4)

将页面导入更改为<%@page import="com.google.gson.JsonObject"%><%@page import="com.google.gson.JSONObject"%>

请注意JSON中的 JSONObject