在 HTML、JAVA、Spring 中保留换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3776279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preserve line breaks in HTML,JAVA,Spring
提问by Mahmoud Saleh
i have a web application built with HTML(front-end),java(server-side) and i have a textarea when posting some data with line breaks (pressing enter after a word) the line breaks are not reserved (the data appears next to each other with no line breaks) how to preserve the line breaks ?, note that i am not using the tag when displaying (have to)
我有一个用 HTML(前端)、java(服务器端)构建的 Web 应用程序,当发布一些带有换行符的数据时我有一个 textarea(在一个单词后按 Enter)换行符不是保留的(数据出现在下一个)彼此之间没有换行符)如何保留换行符?,请注意,我在显示时没有使用标签(必须)
i am using the code server side to convert new lines into br
我正在使用代码服务器端将新行转换为 br
public String saveLineBreaks(String text) {
return text.replaceAll("\n", "<br/>");
}
but it doesn't work properly
但它不能正常工作
采纳答案by Sean Patrick Floyd
This is just a wild guess, as I don't know what web framework you are using etc. but:
这只是一个疯狂的猜测,因为我不知道您使用的是什么 Web 框架等,但是:
Text from a <textarea>
will probably have line breaks (\n
), but HTML will interpret them as whitespace. So on the java side, you need to do something like this:
来自 a 的文本<textarea>
可能会有换行符 ( \n
),但 HTML 会将它们解释为空格。所以在java端,你需要做这样的事情:
String forOutput = input.replace("\n", "<br />\n");
However, in almost every imaginable web framework, there is some utility method that does this for you manually or automatically, so the question is to find the right one for you.
但是,在几乎所有可以想象的 Web 框架中,都有一些实用方法可以手动或自动为您执行此操作,因此问题是找到适合您的方法。
回答by Nithesh Chandra
Maybe \n
isn't the line delimiter. Try using System.getProperty("line.separator")
.
也许\n
不是行分隔符。尝试使用System.getProperty("line.separator")
.