new line doesn't appear when using c out tag

戏子无情 提交于 2020-01-01 05:33:32

问题


I appended "\n" to the String and when using s tag textarea, the newline has been appended and data are shown line by line. But when I use c out tag, data are shown in one line. How can I show line by line using with c out tag?

StringBuffer sb = new StringBuffer();
    for (MyBean bean : beanList) {

                sb.append((bean.getName());
                sb.append("\n");
            }
            return sb.toString();

JSP

<c:out value="${myData}"/>

回答1:


JSP produces HTML. In HTML, new lines are to be represented by the <br> element, not by the linefeed character. Even more, if you look in the average HTML source, you'll see a lot of linefeed characters, but they are by default not interpreted by the webbrowser at all.

Apart from using the HTML <br> element instead of the linefeed character,

sb.append("<br />");

and printing it without <c:out> like so ${myData}, you can also use the HTML <pre> element to preserve whitespace,

<pre><c:out vaule="${myData}" /></pre>

or just apply CSS white-space:pre on the parent element, exactly like the HTML <textarea> element is internally doing:

<span style="white-space:pre"><c:out value="${myData}"/></span>

(note: a class is more recommended than style, the above is just a kickoff example)

The latter two approaches are recommended. HTML code does not belong in Java classes. It belongs in JSP files. Even more, you should probably actually be using JSTL <c:forEach> to iterate over the collection instead of that whole piece of Java code.

<c:forEach items="${beanList}" var="bean">
    <c:out value="${bean.name}" /><br />
</c:forEach>


来源:https://stackoverflow.com/questions/14514440/new-line-doesnt-appear-when-using-c-out-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!