Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have line breaks in text/plain servlet response

I have a servlet that generates some text. The purpose of this is to have a simple status page for an application that can easily be parsed, therefor I'd like to avoid html.

Everything works fine, except that linebreaks get swallowed somewhere in the process.

I tried \r \r\n \n but the result in the browser always looks the same: everything that might look like a line break just disapears and everything is in one looooong line. Which makes it next to impossible to read (both for machines and humans).

Firefox does confirm that the result is of type text/plain

So how do I get line breaks in a text/plain document, that is supposed to be displayed in a browser and generated by a servlet?

update:

Other things that do not work:

  • println

  • System.getProperty("line.separator")

like image 668
Jens Schauder Avatar asked Oct 20 '22 19:10

Jens Schauder


2 Answers

in plain/text it is totally dependent on browser's word-wrap processing

for example:

in firefox

about:config

and set this

plain_text.wrap_long_lines;true

you can't handle it from server, you might want to converting it to html with plain text and line breaks or css magic

like image 77
jmj Avatar answered Oct 27 '22 00:10

jmj


As @gnicker said, I would go for a content type of text-plain like that in your servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    response.setContentType("text/plain");
    // rest of your code...
}

To output a new line, you just use the println function of your ServletOutputStream:

ServletOutputStream out = response.getOutputStream();
out.println("my text in the first line");
out.println("my text in the second line");
out.close

The new line character could be \n or \r\n though you could just stick with the println function.

like image 44
Sebastian Baumhekel Avatar answered Oct 26 '22 23:10

Sebastian Baumhekel