开发者

Storing multiline strings in db and displaying them in web page

I am taking the values 开发者_高级运维from a text area and storing them in database for later display. Current scenario is that the string gets stored with "\n" in the db. Before display I replace all \n characters to

using replaceAll methods. But the problem is when I display it, < and > characters get converted to &lt; and &gt;.

What should be the correct approach to solve this?

comment.replaceAll("\n", "<br>")


You need to disable escaping during display. It's unclear what view technology and/or taglibs you're using, but this is typical for JSTL <c:out> and JSF <h:outputText>. They both by default escape predefined HTML/XML entites, but have an extra attribute to disable escaping.

JSTL:

<c:out value="${bean.text}" escapeXml="false" />

JSF:

<h:outputText value="#{bean.text}" escape="false" />

However, keep XSS attacks in mind for the case that those texts are user-controlled input. You may want to clean it prior to saving in DB with help of for example Jsoup.

By the way, instead of replaceAll() you can also just use CSS white-space: pre; to display the newlines as-is.


You must be aware what you want to do with your string. In you use it in the HTML part of the page, the characters <, > and & must be escaped (which is what you see).

The effect you see can happen because a) you escape the string twice or b) you use an escaped string in a place where it shouldn't be escaped.

You must debug the code to see who escapes the string when.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜