java 如何在 JSP 表达式语言中进行 HTML 编码?

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

How to HTML-encode in the JSP expression language?

javajspelhtml-encode

提问by Martijn

Consider the following piece of JSP:

考虑以下 JSP 片段:

<param name="FlashVars" value="${flashVars}" />

The value of ${flashVars}contains ampersands and needs to be encoded before it is output. Instead, JSP expects the value of ${flashVars}to be a piece of HTML and outputs the ampersands verbatim, resulting in bad HTML.

的值${flashVars}包含与号,需要在输出前进行编码。相反,JSP 期望 的值${flashVars}是一段 HTML 并逐字输出&符号,从而导致错误的 HTML。

I found out that I can get the value to be encoded if I write it like this:

我发现如果我这样写,我可以得到要编码的值:

<param name="FlashVars" value="<c:out value="${flashVars}"/>" />

But this looks really ugly and confuses my IDE to boot. Is there a better way to get the same result?

但这看起来真的很丑,并且让我的 IDE 无法启动。有没有更好的方法来获得相同的结果?

回答by BalusC

Use fn:escapeXml().

使用fn:escapeXml().

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<param name="FlashVars" value="${fn:escapeXml(flashVars)}" />