Issue
I have a list which is pulled from a Postgres database and I need to be able to reference/manipulate it with JavaScript.
I have updated the code as shown below:
Here is the Servlet's doGet method:
protected void doGet(HttpServletRequest req, HttpServletResponse json)
throws ServletException, IOException {
List<Employee> employees = uds.findAll();
req.setAttribute("employees", employees);
json.setContentType("application/json");
json.getWriter().write(String.valueOf(employees));
}
And here is what I currently have in JavaScript:
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(data);
}
}
}
The issue I am having at this point is that the client is not receiving data in JSON format. If I log the data as shown above, the log will produce something along the lines of the following:
[Employee{, employee_id='123456', email='[email protected]', firstName='Juan',
lastName='Terri'}, Employee{, employee_id='2', email='[email protected]',
firstName='Sansa', lastName='Stark'}]
This is the correct data, but not in a useful format.
However, if I try to do console.log(JSON.parse(data))
, then I receive Uncaught SyntaxError: Unexpected token E in JSON at position 1
.
I believe this is a simple syntax error on my part in the servlet, but am unsure of how to fix it.
Solution
For other noobs like me, I've compiled the following complete solution for this issue:
The Servlet should look something like this:
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()
is a method which returns a list of objects. ObjectMapper is a Jackson utility (Gson is another option, I believe). This puts the list into JSON format.
The HTML or JSP should look like this:
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));
}
}
This will get the list of objects in a usable format which you can then manipulate with JavaScript to do whatever you'd like. Hopefully this will help someone!
Answered By - link716