简体   繁体   中英

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

I am trying to pass a JsonObject to jsp. However, I think I cannot get the JsonObject using getAttribute method. How should I do to make this available.

There's a Servlet code, below.

 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.

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

@The Neo Noir Develper

Even I changed redirection to forward It doesn't work and make same error.

Here's servlet code below.

            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.

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

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,

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.

Anyhoo, first, are you sure your session is being carried over? I say this because you are using a redirect instead of a simple RequestDispatcher Forward. A redirect creates a new request.

I think you should set this object in request and use a RequestDispatcher. Similarly, on the JSP side, you should use the request object to get the attribute back.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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