2013-03-18 91 views
0

在servlet im中創建一個JSONObject並將該對象傳遞給JSP。將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中沒有顯示錯誤。我該怎麼辦?由於

+0

'org.json.JSONObject'或'com.google.gson.JsonObject'? – DDK 2013-03-18 09:42:48

+0

@DDK'org.json.JSONObject' – 2013-03-18 09:44:48

+1

嘗試將jsp中的導入標記更改爲'<%@ page import =「org.json.JSONObject」%>' – DDK 2013-03-18 09:46:48

回答

4

更改頁面導入:<%@page import="com.google.gson.JsonObject"%><%@page import="com.google.gson.JSONObject"%>

注意在JSONObjectJSON