h:outputText does not break \r\n characters into new lines

前端 未结 3 1407
广开言路
广开言路 2020-11-29 23:45

I have a String variable which contains carriage returns and new lines \\r\\n.

text = \"Text1\\r\\nText2\\r\\nText3\";
3条回答
  •  猫巷女王i
    2020-11-30 00:32

    Linebreaks in HTML are represented by
    element, not by the \n character. Even more, open the average HTML source code by rightclick, View Source in browser and you'll "see" \n over all place. They are however not presented as such in the final HTML presentation. Only the
    will.

    So, yes, you need to replace them by
    . You can use JSTL functions for this:

    <... xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions">
    
    
    

    Note: when using Apache EL instead of Oracle EL, double-escape the backslash as in \\n.

    
    

    Otherwise you will face an exception with the message Failed to parse the expression with root cause org.apache.el.parser.ParseException: Encountered .

    This all is however ugly and the escape="false" makes it sensitive to XSS attacks if the value comes from enduser input and you don't sanitize it beforehand. A better alternative is to keep using \n and set CSS white-space property to preformatted on the parent element. 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.

    E.g.

    
    
    .preformatted {
        white-space: pre-wrap;
    }
    

提交回复
热议问题