如何将servlet的json输出发送到jsp?
我正在进行库存控制.我试图检查输入的商品数量是否少于库存数量.我正在获取servet json输出.但是我无法将其发送回jsp.
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.
Jsp JQuery代码.
Jsp JQuery code.
<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查询.
And this is servlet query.
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.请帮我解决一下这个.
From both System.out.println() s output is always coming correctly. But not sending to jsp back. Please help me with this.
您必须做的也是一种最佳实践,它是使用需要传递给gson库的属性来创建DTO类.
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.
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.
and inside your loop, set the values to the dto object, then pass it to 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结构. 尝试看看!
gson will give you the proper json structure to the client side. try and see !