从Textarea读取时不保留换行符 [英] Newline not preserved when reading from Textarea
问题描述
我的Java Web应用程序从文本区域获取内容,并通过电子邮件发送内容.
My java webapp fetches content from a textarea, and e-mails the same.
我面临的问题是,使用
request.getParameter("message");
有什么线索可以解决吗?
Any clues how it can be tackled?
TIA.
文本区域中的内容是:
abcd
abcd
The content in the textarea is:
abcd
abcd
代码:
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 loc for message "+message+" using \\r : "+message.indexOf("\r"));
System.out.println("index loc for message "+message+" using \\n\\r : "+message.indexOf("\n\r"));
输出:
使用\ r \ n的邮件asdfasdf的索引位置:-1
使用\ n的消息asdfasdf的索引位置:-1
使用\ r的消息asdfasdf的索引位置:-1
使用\ n \ r:-1
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.
听起来您正在用HTML重新显示它. 原始"换行符不是HTML标记的一部分.右键单击Web浏览器中的查看页面源文件.您会在所有地方看到换行符.通常在HTML标记之前和/或之后.
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.
为了在HTML演示文稿中直观地显示换行符,您实际上应该使用<br>
标记.您可以使用<br>
字符串替换换行符,如下所示:
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>");
这仅对 XSS攻击孔敏感,如果message
是一个用户控制的变量,因为您必须在JSP中不转义地显示它(即不带<c:out>
),以使<br>
正常工作.因此,您需要确保message
变量为
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.
或者,您也可以在此处将CSS white-space
属性设置为将消息重新显示为pre
的位置.如果要将行换行到block元素的上下文中,请设置pre-wrap
.或者,如果您也想折叠空格和制表符,请设置pre-line
.
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).
这篇关于从Textarea读取时不保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!