Java 如何在 JSP 的表达式语言中放置“换行”?

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

How to put "new line" in JSP's Expression Language?

javajspjsfel

提问by Roman Kagan

What would be right EL expression in JSP to have a new line or HTML's <br/>? Here's my code that doesn't work and render with '\n' in text.

JSP 中的正确 EL 表达式有一个新行或 HTML 是<br/>什么?这是我的代码,它不起作用并在文本中使用 '\n' 进行渲染。

<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS}\n#{msg.TCW_SELECT_PART_ANALYSIS2}"/>

采纳答案by Bozho

Since you want to output <br />, just do:

既然你想输出<br />,就做:

<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS}<br />#{msg.TCW_SELECT_PART_ANALYSIS2}" escape="false" />

The attribute escape="false"is there to avoid the <br />being HTML-escaped.

该属性escape="false"是为了避免<br />被 HTML 转义。

You can even display the two messages in separate tags and put the <br />in plain text between them.

您甚至可以在单独的标签中显示两条消息,并<br />在它们之间放置纯文本。

<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS}" />
<br />
<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS2}" />

If you're still on JSF 1.1 or older, then you need to wrap plain HTML in <f:verbatim>like:

如果您仍在使用 JSF 1.1 或更旧的版本,那么您需要将纯 HTML 包装为<f:verbatim>

<f:verbatim><br /></f:verbatim>

回答by Aaron Digulla

How about:

怎么样:

<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS}"/>
<af:outputText value="#{msg.TCW_SELECT_PART_ANALYSIS2}"/>

(i.e. split the value and put the character you want between the two)?

(即拆分值并将您想要的字符放在两者之间)?

回答by Vincent Ramdhanie

If you want a new line in the browser then you need to put "<br/>" in the text. The browser will then interpret it correctly. It does not understand \n.

如果你想在浏览器中换行,那么你需要<br/>在文本中加入“ ”。然后浏览器将正确解释它。它不明白\n。

回答by BacMan

Write a custom function that calls this piece of code:

编写一个调用这段代码的自定义函数:

import java.util.StringTokenizer;

public final class CRLFToHTML {

    public String process(final String text) {

        if (text == null) {
            return null;
        }

        StringBuilder html = new StringBuilder();

        StringTokenizer st = new StringTokenizer(text, "\r\n", true);

        while (st.hasMoreTokens()) {
            String token = st.nextToken();

            if (token.equals("\n")) {
                html.append("<br/>");
            } else if (token.equals("\r")) {    
                // Do nothing    
            } else {    
                html.append(token);    
            }
        }

        return html.toString();

    }

}