Newline not preserved when reading from Textarea
My java webapp fetches content from a textarea, and e-mails the same.
The problem I'm facing is that the newline character in the textarea message is not preserved when reading the same using
request.getParameter("message");
Any clues how it can be tackled?
TIA.
EDIT:
The content in the textarea is:
abcd abcdCODE:
String message = request.getParameter("message");
System.out.println("index loc for message "+message+" using \\r\\n : "+message.indexOf("\r\n"));
System.out.println("index loc for message "+message+" using \\n : "+message.indexOf("\n"));
System.out.println("index 开发者_StackOverflow社区loc for message "+message+" using \\r : "+message.indexOf("\r"));
System.out.println("index loc for message "+message+" using \\n\\r : "+message.indexOf("\n\r"));
OUTPUT:
index loc for message asdfasdf using \r\n : -1
index loc for message asdfasdf using \n : -1 index loc for message asdfasdf using \r : -1 index loc for message asdfasdf using \n\r : -1
That completely depends on how you're redisplaying it.
It sounds like that you're redisplaying it in HTML. "Raw" newlines are not part of HTML markup. Do a rightclick, View Page Source in webbrowser. You'll see linebreaks over all place. Usually before and/or after HTML tags.
In order to visually present linebreaks in the HTML presentation, you should actually be using <br>
tags. You can replace newlines by <br>
strings as below:
message = message.replace("\n", "<br>");
This is only sensitive to XSS attack holes if the message
is an user-controlled variable, because you have to present it unescaped in JSP (i.e. without <c:out>
) in order to get <br>
to work. You thus need to make sure that the message
variable is sanitized beforehand.
Alternatively, you can also set CSS white-space
property there where you're redisplaying the message to pre
. If you'd like to wrap lines inside the context of a block element, then set pre-wrap
. Or if you'd like to collapse spaces and tabs as well, then set pre-line
.
<div id="message"><c:out value="${message}" /></div>
#message {
white-space: pre-line;
}
This will display the text preformatted (as a textarea by default does).
Two possible problems:
The text in the textarea is word wrapped and doesn't really have any newlines.
The String you get with
getParameter()
contains newlines (\n
) but no carriage returns (\r
) as expected by many email programs.
As a first step, I'd try dumping the retrieved String in a way you can check for this. You could write to a file and use od
or a hex editor to look at the file, for example.
If it turns out you're simply missing CRs, you could do some simple regexp-based replacement on the string to fix that.
Searching the ASCII codes i found that the new line is not defined like the often \n
, instead is defined like \r\n
.
Regards.
You need to encodeURIComponent()
before submitting the form and decodeURIComponent()
on the server side.
精彩评论