Replace characters with HTML entities in java

孤者浪人 提交于 2019-12-17 14:53:17

问题


I want to replace certain characters with their respective HTML entities in an HTML response inside a filter. Characters include <, >, &. I can't use replaceAll() as it will replace all characters, even those that are part of HTML tags.

What is the best approach for doing so?


回答1:


From java you may try, Apache Commons Lang (legacy v2) StringEscapeUtils.escapeHtml().
or with commons-lang3: StringEscapeUtils.escapeHtml4().

Please note this also converts à to &agrave; & such




回答2:


If you're using a technology such as JSTL, you can simply print out the value using <c:out value="${myObject.property}"/> and it will be automatically escaped.

The attribute escapeXml is true by default.

escapeXml - Determines whether characters <,>,&,'," in the resulting string should be converted to their corresponding character entity codes. Default value is true.

http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/



来源:https://stackoverflow.com/questions/10978098/replace-characters-with-html-entities-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!