Junior
How to insert a line break in HTML using JSP?
sobes.tech AI
Answer from AI
You can use the <br> tag.
<%
// Output text with line break
out.println("First line.<br>");
out.println("Second line.");
%>
Another way is to use CSS to control text display.
<p style="white-space: pre-line;">
This line will be broken.<br>
And this one will not, because <br> inside pre-line preserves line breaks.
</p>
You can also use Java code inside JSP to generate a string with a line break character (\n), and then display it so that the browser interprets \n as a line break (e.g., inside <pre> or with CSS white-space: pre-wrap;).
<%
String text = "First line.\nSecond line.";
%>
<pre>
<%= text %>
</pre>
<p style="white-space: pre-wrap;">
<%= text %>
</p>
Main approaches summarized in a table:
| Method | Description | HTML/CSS | JSP/Java | Notes |
|---|---|---|---|---|
<br> |
Inserts explicit line break | Yes | Yes | Simple and common |
CSS white-space: pre-line; |
Preserves line breaks in source | Yes | Yes | Good for formatted text |
CSS white-space: pre-wrap; |
Preserves line breaks and spaces | Yes | Yes | Suitable for preformatted text |
<pre> |
Displays text in monospace with preserved whitespace | Yes | Yes | Semantically for preformatted text |