[英]How to send Json to JSP from servlet , with out converting it to a String
[英]How to send json ouput from servlet to jsp?
我正在进行库存控制。 我试图检查输入的商品数量是否少于库存数量。 我正在获取servet json输出。 但是我无法将其发送回jsp。
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>
这是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
。
要做的也是一种最佳实践,它是使用需要传递给gson库的属性来创建DTO类。
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结构。 尝试看看!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.