在表达式语言中转义 JavaScript [英] Escape JavaScript in Expression Language
问题描述
有时,我需要在 JSF 页面中使用 EL 呈现 JavaScript 变量.
Sometimes, I need to render a JavaScript variable using EL in a JSF page.
例如
<script>var foo = '#{bean.foo}';</script>
或
<h:xxx ... onclick="foo('#{bean.foo}')" />
当 EL 表达式计算结果为包含 JS 特殊字符(如撇号和换行符)的字符串时,这会失败并出现 JS 语法错误.我该如何逃脱?
This fails with a JS syntax error when the EL expression evaluates to a string containing JS special characters such as apostrophe and newline. How do I escape it?
推荐答案
您可以使用 Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript()
EL 中的方法.
You can use Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript()
method for this in EL.
首先创建一个/WEB-INF/functions.taglib.xml
,如下所示:
First create a /WEB-INF/functions.taglib.xml
which look like this:
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
version="2.0">
<namespace>http://example.com/functions</namespace>
<function>
<name>escapeJS</name>
<function-class>org.apache.commons.lang3.StringEscapeUtils</function-class>
<function-signature>java.lang.String escapeEcmaScript(java.lang.String)</function-signature>
</function>
</taglib>
然后在/WEB-INF/web.xml
中注册如下:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/functions.taglib.xml</param-value>
</context-param>
那么你就可以这样使用了:
Then you can use it as follows:
<html ... xmlns:func="http://example.com/functions">
...
<script>var foo = '#{func:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{func:escapeJS(bean.foo)}')" />
或者,如果您碰巧已经使用 JSF 实用程序库 OmniFaces,那么您也可以使用其内置的 of:escapeJS()
函数:
Alternatively, if you happen to already use the JSF utility library OmniFaces, then you can also just use its builtin of:escapeJS()
function:
<html ... xmlns:of="http://omnifaces.org/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />
这篇关于在表达式语言中转义 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!