【发布时间】:2016-02-29 01:51:22
【问题描述】:
我正在尝试将 JsonObject 传递给 jsp。但是,我认为我无法使用 getAttribute 方法获取 JsonObject。我应该怎么做才能使它可用。
下面有一个 Servlet 代码。
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
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 javax.servlet.http.HttpSession;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@WebServlet("/ShapeRendererFileManager")
public class ShapeRendererFileManager extends HttpServlet {
private static final long serialVersionUID = 1L;
HttpSession session;
//Send Json to jsp
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=euc-kr");
session = request.getSession(true);
//System.out.println(request.getParameter("tmp").toString());
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "jinny");
jsonObject.addProperty("title", "web");
session.setAttribute("jsonObject", jsonObject);
response.sendRedirect("index.jsp");
}
}
下面有一个jsp代码。
<%@page import="com.google.gson.JsonObject"%>
<%@page import="com.google.gson.JsonElement"%>
<%@page import="com.google.gson.JsonArray"%>
<!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=EUC-KR">
<title>start page</title>
</head>
<%
request.setCharacterEncoding("euc-kr");
response.setContentType("text/html;charset=euc-kr");
String tmp = "";
JsonObject json = (JsonObject)session.getAttribute("jsonObject");
tmp = json.get("name").toString(); //error at this line
%>
<body>
<script>
$(function(){
document.getElementByName("formtag").action="ShapeRendererFileManager";
document.getElementById("formtag").submit();
})
</script>
<h1><%= tmp %></h1>
<form name="formtag" action="" method="post">
</form>
</body>
</html>
提前致谢。
【问题讨论】:
-
可以显示JSON格式吗?
-
你在 json.get("name").toString(); 处得到 nullpointerexception;
-
如果json对象和flow一样是一次性的,应该使用response.forward(req,res);更好的方法,而不是在会话中设置 jsonObject。
-
@The Neo Noir Developer 是的,我在包含 "json.get("name").toString();" 的行上得到了 nullpointerexception
-
@SpringLearner 我的 Json 对象在 Servlet 代码中 ~ :)