Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

jsf - Escape JavaScript in Expression Language

Sometimes, I need to render a JavaScript variable using EL in a JSF page.

E.g.

<script>var foo = '#{bean.foo}';</script>

or

<h:xxx ... onclick="foo('#{bean.foo}')" />

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript() method for this in EL.

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>

Then register it in /WEB-INF/web.xml as follows:

<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)}')" />

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)}')" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...