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

时间:2022-03-15 11:48:29

I'm making an inventory control. I was trying to check if the entered quantity of item is less than the stock quantity or not. I'm getting the servet json output. But I can't send it to jsp back.

我正在进行库存控制。我试图检查输入的商品数量是否小于库存数量。我正在获得servet json输出。但是我不能把它发送给jsp了。

Jsp JQuery code.

Jsp JQuery代码。

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

And this is servlet query.

这是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);
                }
            }


From both System.out.println() s output is always coming correctly. But not sending to jsp back. Please help me with this.

从System.out.println()输出总是正确的输出。但是没有送回jsp。请帮我解决一下这个。

2 个解决方案

#1


1  

what you have to do and also a best practice is to create a DTO class with the properties that you need to pass to gson library.

你需要做什么,最好的做法是创建一个DTO类,其中包含你需要传递给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
   }

and inside your loop, set the values to the dto object, then pass it to gson.

在循环内部,将值设置为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 will give you the proper json structure to the client side. try and see !

gson将为客户端提供适当的json结构。试试看!

#2


1  

Gson allows strings and numbers to serialize to JSON by themselves (which is probably ok by the definition), but a lot of other libraries would consider this invalid JSON.

Gson允许字符串和数字自己序列化为JSON(定义可能没问题),但是很多其他库会考虑这个无效的JSON。

Try wrapping your response in an object so that the response is {"id": 5} and not just 5.

尝试将响应包装在一个对象中,以便响应为{“id”:5},而不仅仅是5。

#1


1  

what you have to do and also a best practice is to create a DTO class with the properties that you need to pass to gson library.

你需要做什么,最好的做法是创建一个DTO类,其中包含你需要传递给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
   }

and inside your loop, set the values to the dto object, then pass it to gson.

在循环内部,将值设置为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 will give you the proper json structure to the client side. try and see !

gson将为客户端提供适当的json结构。试试看!

#2


1  

Gson allows strings and numbers to serialize to JSON by themselves (which is probably ok by the definition), but a lot of other libraries would consider this invalid JSON.

Gson允许字符串和数字自己序列化为JSON(定义可能没问题),但是很多其他库会考虑这个无效的JSON。

Try wrapping your response in an object so that the response is {"id": 5} and not just 5.

尝试将响应包装在一个对象中,以便响应为{“id”:5},而不仅仅是5。