如何将 json 输出从 servlet 发送到 jsp?

How to send json ouput from servlet to jsp?

我正在进行库存控制。我试图检查输入的商品数量是否少于库存数量。我得到 servet json 输出。但我无法将它发送回 jsp。

JspJQuery代码.

<script>
        $('document').ready(function() {
            $('#submit_btn').click((function() {
                var $name = $("select#item_name").val();
                var $qty = $("input#qty").val();

                $.post('BuyItem', {item_name: $name, item_qty: $qty}, function(data) {
                    if (data !== null) {
                        alert(text(data));
                        $("input#qty").val("");
                    } else {
                        alert("Invalid Item!");
                    }
                }
                );
            }));
        });
    </script>

这是 servlet 查询。

   while (rs.next()) {

                if (rs.getInt("qty") > qty) {
                    int id = rs.getInt("item_id");
                    Gson gson = new Gson();
                    String json = gson.toJson(id);
                   // System.out.println("one" + json);
                    response.setContentType("application/json");
                    //            response.setCharacterEncoding("UTF-8");
                    response.getWriter().print(json);
                } else {
                    Gson gson = new Gson();
                    String json = gson.toJson("Stock doesn\'t have enough item quantity.");
                  //  System.out.println("two" + json);
                    response.setContentType("application/json");
                    //          response.setCharacterEncoding("UTF-8");
                    response.getWriter().print(json);
                }
            }


System.out.println() 的输出总是正确的。但不发送给 jsp 回来。请帮我解决一下这个。

Gson 允许字符串和数字自行序列化为 JSON(根据定义可能没问题),但许多其他库会认为这是无效的 JSON.

尝试将您的响应包装在一个对象中,以便响应是 {"id": 5} 而不仅仅是 5.

您必须做的也是最佳做法是创建一个 DTO class,其中包含您需要传递给 gson 库的属性。

    public class ResponseDTO implements Serializable{
          private Integer id;
          //more properties ...

          public Integer getId() {
            return id;
          }
          public void setId(Integer id) {
              this.id= id;
          }  

           // other getters & setters
   }

在循环中,将值设置为 dto 对象,然后将其传递给 gson。

Gson gson = new Gson();
          ResponseDTO dto = null;
          String json = "";
          response.setContentType("application/json");
          ......
          if (rs.getInt("qty") > qty) {
                dto = new ResponseDTO();
                int id = rs.getInt("item_id");
                dto.setId(id); 
                ......

                json = gson.toJson(dto);            
            } else {
               ...... // similar
                json = gson.toJson("{data: 'Some message'}");
            }
        response.getWriter().print(json);

gson 将为您提供正确的 json 客户端结构。 试试看!