java 在spring messages.properties中,当使用错误代码作为key时,如何保证错误信息的换行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1816461/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:06:26  来源:igfitidea点击:

In a spring messages.properties, how to ensure line break of error message when using an error code as key?

javaspringjspspring-mvc

提问by Champ

In messages.properties:

messages.properties

error.code=This is error message.\nThis is next line of error message.

Now, when I set "errors.rejectValue" with this "error.code" for a form field, I cannot get the line break of '\n'to display on the jsp page when displaying the error message using the form:errorselement.

现在,当我errors.rejectValue用这个“ error.code”为表单字段设置“ ”时,当'\n'使用form:errors元素显示错误消息时,我无法在jsp页面上显示的换行符。

Instead of '\n', using <br/>also does not work and gets displayed as is on the page.

而不是'\n',使用<br/>也不起作用并按原样显示在页面上。

回答by samitgaur

In order to display a <br>as a line break, or for any other html tag in the error message body to take effect e.g. a <b>, simply turn html escaping off at tag level by adding htmlEscape="false"to your form:errorselement.

为了将 a 显示<br>为换行符,或为了使错误消息正文中的任何其他 html 标签生效,例如 a <b>,只需通过添加htmlEscape="false"到您的form:errors元素来关闭标签级别的 html 转义。

回答by work.paul

i had the same problem while loading the messages from the database, meaning that the '\n' (new line) sequence was escaped. so here is the sample solution, replace the "\\n" with "\n" :

我在从数据库加载消息时遇到了同样的问题,这意味着 '\n'(新行)序列被转义了。所以这是示例解决方案,将 "\\n" 替换为 "\n" :

String twoLinesMessage=((String)context.getMessage("error.code", null, locale)).replace("\n","\n"); 

回答by skaffman

The layout of distinct lines in an HTML page is not really something that a message bundle can deal with, it's just not suitable for the task. If you need multiple lines to be displayed, then realistically you're going to need multiple messages, with multiple entries in the properties file.

HTML 页面中不同行的布局实际上并不是消息包可以处理的,它只是不适合该任务。如果您需要显示多行,那么实际上您将需要多条消息,在属性文件中有多个条目。

Perhaps you could cook up something which iterates over a sequence of properties, with something like this in your properties file:

也许您可以编写一些迭代一系列属性的东西,在您的属性文件中使用以下内容:

error.code.1=This is error message.
error.code.2=This is next line of error message.

It then becomes the job of the JSP to render the sequence of messages. Not very elegant, though, but I can't think of a better solution right now :)

然后,呈现消息序列就成为 JSP 的工作。虽然不是很优雅,但我现在想不出更好的解决方案:)

回答by Bozho

Extending the spring tag form:errorsand adding conversion from \nto <br />is also a non-beatiful solution, but one that will probably work.

扩展 spring 标签form:errors并添加从\nto 的转换<br />也是一种不完美的解决方案,但可能会奏效。