简体   繁体   English

我无法从 servlet 获取 json 对象到 jsp。 我能怎么做?

[英]I can't get a json object from servlet to jsp. How can I do?

I am trying to pass a JsonObject to jsp.我正在尝试将 JsonObject 传递给 jsp。 However, I think I cannot get the JsonObject using getAttribute method.但是,我认为我无法使用 getAttribute 方法获取 JsonObject。 How should I do to make this available.我该怎么做才能使它可用。

There's a Servlet code, below.下面有一个 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");
    }
 }

There's a jsp code below.下面是一个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>

Thanks in advance.提前致谢。

Here just a sample by use google Gson library.这里只是一个使用谷歌 Gson 库的示例。 you can download that lib here or here您可以 在此处此处下载该库

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   HashMap<Object, Object> obj=new HashMap<>();
    obj.put("name", "Janny");
    obj.put("title", "Coder");

    String jsonObject=new Gson().toJson(obj);
    System.out.println(jsonObject);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    session.setAttribute("jsonObject",jsonObject);
    request.getRequestDispatcher("index.jsp").forward(request, response);
}

Anyway, you can use Ajax to loop data or use JSTL!反正你可以用ajax循环数据也可以用JSTL!

@The Neo Noir Develper @The Neo Noir 开发者

Even I changed redirection to forward It doesn't work and make same error.即使我将重定向更改为转发它也不起作用并犯同样的错误。

Here's servlet code below.下面是servlet代码。

            protected void doGet(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);

    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);
}

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);

    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);

    //response.sendRedirect("index.jsp");

}

There's jsp code below.下面是jsp代码。

    <%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" %>
    <%@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");
    JsonObject json = (JsonObject)session.getAttribute("jsonObject");
    String tmp = json.get("name").toString(); //error at this line
%>
<body>
<!-- <div id="main_page">
</div> 
<script data-main="main" src="libs/require-2.1.11.js"></script>  -->

<script>
    $(function(){
        document.getElementByName("formtag").method="POST";
        document.getElementByName("formtag").action="ShapeRendererFileManager";
        document.getElementById("formtag").submit();
    });
</script>

<h1><%= tmp %></h1>
<form name="formtag" action="" method="post">
</form>

</body>
</html>

Could you please try to use the below code in your servlet instead of sendRedirect您能否尝试在您的 servlet 中使用以下代码而不是 sendRedirect

RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);

and also check the jsonObject in your jsp for null either you are getting null or not from session attribute,并检查您的jsp中的jsonObject是否为null,无论您是否从会话属性中获取null,

JsonObject json = (JsonObject)session.getAttribute("jsonObject");

after doing above changes if you will again get the error then please post the error stack.完成上述更改后,如果您再次收到错误,请发布错误堆栈。

您可以尝试更改回复的内容类型吗

response.setContentType("application/json");

There are multiple things wrong in your code.您的代码中有很多错误。 Apart from using scriptlets.除了使用scriptlet。

Anyhoo, first, are you sure your session is being carried over? Anyhoo,首先,您确定您的会话正在继续吗? I say this because you are using a redirect instead of a simple RequestDispatcher Forward.我这样说是因为您使用的是重定向而不是简单的 RequestDispatcher Forward。 A redirect creates a new request.重定向会创建一个新请求。

I think you should set this object in request and use a RequestDispatcher.我认为您应该在请求中设置此对象并使用 RequestDispatcher。 Similarly, on the JSP side, you should use the request object to get the attribute back.同样,在 JSP 端,您应该使用请求对象来取回属性。

Without much info of how the session is created, it would be hard to pinpoint whether the session is being maintained at all or not.如果没有关于如何创建会话的太多信息,就很难确定会话是否正在维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM