如何将JSP请求的XML数据格式化为表 [英] How to format XML data that is requested from a JSP into a table
问题描述
我有一个.jsp,它确定用户可以访问哪些特定内容.它创建一个XML文件,该文件将被先前的jsp读入流中.如何将读取到char数组流中的XML数据填充到表中?
I have a .jsp which determines what specific things a user has access to. It creates an XML file which is read into a stream by the previous jsp. How would I populate a table with the XML data which is read into a char array stream?
推荐答案
有很多方法可以从XML文件中获取HTML表.一种最干净的方法是将XML解析为传递给JSP的可重复使用的 javabeans 的集合,以便您可以在呈现HTML表时使用 JSTL <c:forEach>
对其进行迭代.这样,每一层都保持自己的明确责任. JAXB 提供的Java SE在此方面非常有帮助.
There are a lot of ways to get a HTML table out of the XML file. One of the most clean ways is to parse that XML into a collection of reuseable javabeans which you pass to the JSP, so that you can use JSTL <c:forEach>
to iterate over it while rendering a HTML table. This way every layer keeps its own clear responsibility. The Java SE provided JAXB is very helpful in this.
想象一下您的XML看起来像这样:
Imagine that your XML look like this:
<data>
<entry>
<key>foo1</key>
<value>bar1</value>
</entry>
<entry>
<key>foo2</key>
<value>bar2</value>
</entry>
<entry>
<key>foo3</key>
<value>bar3</value>
</entry>
</data>
然后,您可以按以下方式创建JAXB javabean:
Then you can create a JAXB javabean as follows:
@XmlRootElement
public class Data {
@XmlElement(name="entry")
private List<Entry> entries;
public List<Entry> getEntries() {
return entries;
}
public static class Entry {
@XmlElement
private String key;
@XmlElement
private String value;
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
}
然后您可以将其转换为List<Entry>
,如下所示:
Then you can transform it into a List<Entry>
as follows:
List<Entry> entries = JAXBContext.newInstance(Data.class).createUnmarshaller().unmarshal(inputStream).getEntries();
然后,您可以在转发请求之前,将 servlet (或JSP?:/)存储在请求范围中到JSP:
Then you can let your servlet (or JSP? :/ ) store it in the request scope before forwarding the request to the JSP:
request.setAttribute("entries", entries);
最后,您可以在JSP中对其进行迭代,并将其显示为HTML表:
Finally you can in JSP iterate over it and present it as a HTML table:
<table>
<c:forEach items="${entries}" var="entry">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><c:out value="${entry.value}" /></td>
</tr>
</c:forEach>
</table>
这篇关于如何将JSP请求的XML数据格式化为表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!