3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
你應(yīng)該使用 request.getAttribute():
<% List<Employee> theEmployees = request.getAttribute("employees");%>
但是如果你想在你的 javascript 中有效地使用它,建議將它轉(zhuǎn)換為 json。

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
嘗試將您的 servlet 響應(yīng)更改為 json 并使用 Ajax 獲取數(shù)據(jù)這是一個(gè)示例!
var ajax = new XMLHttpRequest();
ajax.open("GET", "your_url_here", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
對(duì)于像我這樣的其他菜鳥(niǎo),我已經(jīng)為這個(gè)問(wèn)題編制了以下完整的解決方案:
Servlet 應(yīng)該看起來(lái)像這樣:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("application/json");
List<Employee> employees = uds.findAll();
String json = new ObjectMapper().writeValueAsString(employees);
resp.getWriter().write(json);
uds.findAll()是一個(gè)返回對(duì)象列表的方法。ObjectMapper 是 Jackson 實(shí)用程序(我相信 Gson 是另一種選擇)。這會(huì)將列表放入 JSON 格式。
HTML 或 JSP 應(yīng)如下所示:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(JSON.parse(data));
}
}
這將以可用格式獲取對(duì)象列表,然后您可以使用 JavaScript 對(duì)其進(jìn)行操作以執(zhí)行任何您喜歡的操作。希望這會(huì)幫助別人!
添加回答
舉報(bào)