Java 在 html 表中输出 JSON 数组(一个 jsp 页面)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3751118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
output JSON array in a html table(a jsp page)
提问by Jonathan
As the title suggested, how do I output a JSON array correctly in a table from a JSP page?
正如标题所暗示的那样,如何在 JSP 页面的表中正确输出 JSON 数组?
Right now whenever I display the JSON array object using <c:out value="${jsonArray}"/>
but it just displays the whole contents of it in JSON string i.e {name: hello, address: baker street }
but what I want to do is somehow parse this and display the info appropriately like this:
现在,每当我使用显示 JSON 数组对象时<c:out value="${jsonArray}"/>
,它只是在 JSON 字符串中显示它的全部内容,即{name: hello, address: baker street }
但我想要做的是以某种方式解析它并像这样适当地显示信息:
**name** **address**
hello baker street
spring java
tim sun
Is it possible in JSTL? I am new to JSTL stuff.
在 JSTL 中可能吗?我是 JSTL 的新手。
package com.kc.models;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class FileObject {
private String filename;
private String type;
private double size;
private Blob file;
private int id;
private String os;
private String description;
public FileObject() {
}
/**
* Constructor for use in returning just the list of files without the
* actual content
*
* @param name
* @param size
* @param id
* @param type
*/
public FileObject(String name, double size, int id, String type) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
}
/**
* Constructor used to create a fileObject with all its properties assigned
*
* @param name
* @param size
* @param id
* @param type
* @param file
*/
public FileObject(String name, double size, int id, String type, Blob file,
String os, String description) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
this.file = file;
this.os = os;
this.description = description;
}
public FileObject(String description){
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String fileName) {
this.filename = fileName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
String fileType = ServletRequestUtils.getRequiredStringParameter(request, "fileType");
//testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList(fileType) );
}
/**
* Get file list from sql server based on type
* @return file list in json
*/
private JSONArray getFileList(String type) {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList(type);
}
public JSONArray getFileList(String type) {
return constructJsonArray(dbFileHelper.getFileList(type));
}
private JSONArray constructJsonArray(List<FileObject> fileList) {
JSONArray mJsonArray = new JSONArray();
JSONObject mJsonFileObject = new JSONObject();
for (int i = 0; i < fileList.size(); i++) {
mJsonFileObject.put("FileObject", fileList.get(i));
System.out.println("File ID = " + fileList.get(i).getId());
System.out.println("fileName = " + fileList.get(i).getFilename());
System.out.println("type = " + fileList.get(i).getType());
System.out.println("size = " + fileList.get(i).getSize());
mJsonArray.add(mJsonFileObject);
}
return mJsonArray;
}
here is my jsp page:
这是我的jsp页面:
<%@ include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var files = "${jsonArray}";
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(files).each(function(i, file) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(file.filename))
.append($('<td/>').text(file.id))
.append($('<td/>').text(file.type))
.append($('<td/>').text(file.size))
.append($('<td/>').text(file.os));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
edit: here is my json output:
编辑:这是我的 json 输出:
var files = [{"FileObject":{"description":"","file":null,"filename":"ACG Simulator(firefox).jpg","id":6,"os":"","size":172,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"car.jpg","id":11,"os":"","size":152,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted.jpg","id":13,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted2.jpg","id":14,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts options.jpg","id":15,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"edit contact view.jpg","id":17,"os":"","size":52,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"fileObject.jpg","id":20,"os":"","size":30,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"groups.jpg","id":27,"os":"","size":31,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"inside contacts.jpg","id":31,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Music highlighted.jpg","id":37,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music options view.jpg","id":38,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music phone view.jpg","id":39,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music vault view.jpg","id":40,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"nice.jpg","id":41,"os":"","size":225,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo highlighted.jpg","id":42,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo options view.jpg","id":43,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo preview view.jpg","id":44,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos phone view.jpg","id":45,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos vault view.jpg","id":46,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"svn error.jpg","id":54,"os":"","size":35,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Video Highlighted.jpg","id":55,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Videos options view.jpg","id":56,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos phone view.jpg","id":57,"os":"","size":50,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos Vault view.jpg","id":58,"os":"","size":49,"type":"jpg"}}]
回答by Andreas
Assuming:
假设:
jsonArray = [ {name: 'hello', address: 'baker street'}, ... ];
One way to do it is to construct the html in Javascript code like this:
一种方法是在 Javascript 代码中构造 html,如下所示:
var myHTMLStr = '<table>';
for(var i in jsonArray) {
myHTMLStr+='<tr><td>' + jsonArray[i]['name'] + '</td><td>' + jsonArray[i]['address'] + '</td></tr>';
}
myHTMLStr+='</table>';
Now display the HTML string:
现在显示 HTML 字符串:
document.getElementById('tableOutput').innerHTML = myHTMLStr;
回答by BalusC
Your question is too ambigious to give a suitable answer, so I'll cover all possible scenarios:
您的问题太含糊,无法给出合适的答案,因此我将涵盖所有可能的情况:
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": "Hyman Doe", "address": "Church Street 1" } ];
I'd suggest to use jQueryto create a HTML table out of it. Here's an SSCCE, you can copy'n'paste'n'run 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": "Hyman 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>
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\": \"Hyman Doe\", \"address\": \"Church Street 1\" }" + "]";
Then I suggest to use a JSON parser to get a
List<Person>
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
<c:forEach>
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>
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)); }); }); });
你把它作为一个 JavaScript 变量,像这样:
var persons = [ { "name": "John Doe", "address": "Main Street 1" }, { "name": "Jane Doe", "address": "Baker Street 1" }, { "name": "Hyman Doe", "address": "Church Street 1" } ];
我建议使用jQuery从中创建一个 HTML 表。这是一个SSCCE,你可以复制'n'paste'n'run它:
<!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": "Hyman 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>
您将其作为 Java String 变量使用,如下所示:
String jsonPersons = "[" + "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" }," + "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" }," + "{ \"name\": \"Hyman Doe\", \"address\": \"Church Street 1\" }" + "]";
然后我建议使用 JSON 解析器来解决
List<Person>
它,比如Google Gson:List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>() {}.getType());
凡
Person
类是这样的:public class Person { private String name; private String address; // Add or generate getters/setters. }
让 servlet 将其放入请求范围并转发到 JSP 进行显示,如下所示:
request.setAttribute("persons", persons); request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
在 JSP 中,使用 JSTL
<c:forEach>
对其进行迭代:<%@ 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>
同 2),你把它作为一个 Java 变量,但你想在 JSP 中通过 Ajax 获取它。然后创建一个 Servlet 类,它在
doGet()
方法中执行以下操作:response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().write(jsonPersons);
并通过 jQuery Ajax 使用回调调用它,其作用与 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)); }); }); });