admin管理员组文章数量:1342918
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?
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?
Share Improve this question edited Jun 8, 2015 at 14:57 BalusC 1.1m376 gold badges3.7k silver badges3.6k bronze badges asked Jul 7, 2011 at 21:03 OntonomoOntonomo 5572 gold badges8 silver badges12 bronze badges 2- The answer below put me on the correct track. – Ontonomo Commented Jul 8, 2011 at 12:51
- added: xmlns:fn="java.sun./jsp/jstl/functions" and in the code '#{fn:replace(_selectedItem.item.webName,"'","")}', – Ontonomo Commented Jul 8, 2011 at 12:52
2 Answers
Reset to default 14You 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./xml/ns/javaee"
xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun./xml/ns/javaee http://java.sun./xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
version="2.0">
<namespace>http://example./functions</namespace>
<function>
<name>escapeJS</name>
<function-class>org.apache.mons.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./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/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />
Have you tried \'#{_selectedItem.item.webName}\',
?
本文标签: jsfEscape JavaScript in Expression LanguageStack Overflow
版权声明:本文标题:jsf - Escape JavaScript in Expression Language - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743633310a2513476.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论