Jens Schauder
Jens Schauder

Reputation: 81950

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:

Upvotes: 6

Views: 10997

Answers (3)

Jens Schauder
Jens Schauder

Reputation: 81950

Sorry, once again it was my mistake.

We have a compressing Servlet Filter configured which removed the linebreaks.

Without that filter \n works just fine.

Upvotes: 1

Sebastian Baumhekel
Sebastian Baumhekel

Reputation: 546

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.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240908

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

Upvotes: 1

Related Questions