user2094311
user2094311

Reputation:

Pass JSONObject to JSP and print the data

In servlet im creating a JSONObject and passing that object to 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);

And this is my JSP Page

<%@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>

But JSP page showing error that JSONObject cannot be resolved to a type. But i have added the jar file and in Servlet it is not showing error. What should I do? Thanks

Upvotes: 0

Views: 11782

Answers (1)

Rasabihari Kumar
Rasabihari Kumar

Reputation: 491

Change the page import: <%@page import="com.google.gson.JsonObject"%> to <%@page import="com.google.gson.JSONObject"%>

Notice the JSON in JSONObject.

Upvotes: 3

Related Questions