I\'m newbie to jsp. I have a JSON
coding
{\"eventDetails\":[{\"startDate\":1387175589253,\"eventJSON\":\"{\\\"userIp\\\":\\\"***.***.***.**\\\"
You have it as a JavaScript variable like so:
var persons = [ { "name": "John Doe", "address": "Main Street 1" }, { "name": "Jane Doe", "address": "Baker Street 1" }, { "name": "Jack Doe", "address": "Church Street 1" } ];
I'd suggest to use jQuery to create a HTML table out of it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(persons).each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
2. You have it as a Java String variable like so:
String jsonPersons = "["
+ "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" },"
+ "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" },"
+ "{ \"name\": \"Jack Doe\", \"address\": \"Church Street 1\" }"
+ "]";
Then I suggest to use a JSON parser to get a List out of it, like Google Gson:
List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>() {}.getType());
Where the Person class look like this:
public class Person {
private String name;
private String address;
// Add or generate getters/setters.
}
Let the servlet put it in the request scope and forward to JSP for display like so:
request.setAttribute("persons", persons);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
In JSP, use JSTL to iterate over it:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.address}</td>
</tr>
</c:forEach>
</table>
3 Same as 2), you have it as a Java variable, but you'd like to obtain it by Ajax in JSP. Then create a Servlet class which does the following in doGet() method:
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(jsonPersons);
And call it by jQuery Ajax with a callback which does the same as 1).
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$.getJSON('url/to/servlet', function(persons) {
persons.each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
});