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}"/>
Creating a new line in HTML code If you are writing the HTML, you can create a new line using the <br> (break) tag, as shown in the example below.
If you want a new line in the browser then you need to put " <br/> " in the text. The browser will then interpret it correctly.
The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It will display the result of an expression, similar to the way < %=... % > work. The < c:out > tag automatically escape the XML tags.
The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java. util. Map object.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With