Issue
If I use method println()
for writing to a file or console, it writes a message and terminates. Easy enough. But now I want it to write to HTML page using Servlet class. Code:
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
for (int i = 0; i < 1000; i++) {
pw.println("hello " + i);
}
}
What I was expected is to get message printed in each line (as if I used <br>
), like this:
hello 0
hello 1
hello 2
hello 3
...
Can someone tell me why isn't every message printed in new line? While if I had used this same code for writing to a file or system.out, it would get desired output. Meaning why I need to put <br>
for this code to work that way, even thought I am using println()
which should implicitly do that?
Solution
If you look at the HTML, you'll see newlines in there. But when rendered in a browser, the browser ignores whitespace and converts it to a single space. See this snippet:
<body>
<div>
Hey
Jude
don't
be
afraid
</div>
</body>
Answered By - David P. Caldwell
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)