[英]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.