你可以使用AJAX(使用jQuery很容易),撥打電話到你的servlet現在
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { param1: "val1" , param2: "val2" }
}).done(function(data) {
//TODO
});
}
在Servlet中,在doPost()
,使用GSON產生JSON表示您的收藏
String parameter1 = request.getParameter(param1);
String parameter2 = request.getParameter(param2);
//call to service to generate the collection
//for example List<Employee>
List<Employee> employees = someService(parameter1, parameter2);
//using google's gson
Gson gson = new Gson();
String json = new Gson().toJson(employees);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
現在我們在javascript函數中作爲javascript對象數組的響應,所以修改爲
}).done(function(data) {
//some processing for display
var len = data.length
for (var i=0; i<len; ++i) {
var employeeFirstName = data[i].firstName;
var employeeLastName = data[i].lastName;
//set it to some DIV, or do the processing you want
}
}
});
另請參見
我不確定這是否適用:將數據序列化爲JSON並使用AJAX加載數據;然後使用Javascript來顯示收到的JSON中的數據。 – nhahtdh
或者,您可以使用嵌入當前JSP頁面的iframe(顯示另一個處理您的java List數據的JSP頁面)。 AJAX是另一種選擇。 –