逃避表达式语言中的JavaScript

Ont*_*omo 5 javascript jsf escaping el

有时,我需要在JSF页面中使用EL呈现JavaScript变量.

例如

<script>var foo = '#{bean.foo}';</script>
Run Code Online (Sandbox Code Playgroud)

要么

<h:xxx ... onclick="foo('#{bean.foo}')" />
Run Code Online (Sandbox Code Playgroud)

当EL表达式求值为包含JS特殊字符(如撇号和换行符)的字符串时,这会导致JS语法错误.我怎么逃避它?

Bal*_*usC 14

您可以在EL中使用Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript()方法.

首先创建一个/WEB-INF/functions.taglib.xml如下所示:

<?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>
Run Code Online (Sandbox Code Playgroud)

然后注册/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>
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它如下:

<html ... xmlns:func="http://example.com/functions">
...
<script>var foo = '#{func:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{func:escapeJS(bean.foo)}')" />
Run Code Online (Sandbox Code Playgroud)

或者,如果你碰巧已经使用了JSF实用程序库OmniFaces,那么你也可以使用它的内置of:escapeJS()函数:

<html ... xmlns:of="http://omnifaces.org/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />
Run Code Online (Sandbox Code Playgroud)