Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new line doesn't appear when using c out tag

Tags:

html

jsp

jstl

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}"/>
like image 834
kitokid Avatar asked Jan 25 '13 02:01

kitokid


People also ask

What tag prints a new line?

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.

How do I create a new line in JSP?

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.

Which attribute is used with c out?

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.

What is c set tag?

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.


1 Answers

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>
like image 197
BalusC Avatar answered Oct 28 '22 18:10

BalusC