如何在 JSP 上转义撇号或引号(由 JavaScript 使用)

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

How to escape apostrophe or quotes on a JSP (used by JavaScript)

javajavascriptformsjspescaping

提问by Caroline

I have a user form. If the user types in a string with 'or "as part of it I have no problem. The form is submitted and saved correctly to the database. My problem is when I reload the page (all entries can be modified and are loaded into a list in the JSP before being displayed). On loading the page I get an error saying:

我有一个用户表单。如果用户输入一个字符串'"作为它的一部分,我没有问题。表单已提交并正确保存到数据库中。我的问题是当我重新加载页面时(所有条目都可以修改并在显示之前加载到 JSP 中的列表中)。在加载页面时,我收到一条错误消息:

missing ) after argument list 'Caroline's message', \n

What do I need to do to escape this string for displaying it on the frontend?

我需要做什么来转义这个字符串以在前端显示它?

Here is the code I am using on the frontend to read in the data and store it in a JavaScript object. I am not fully sure where I need to escape. The field causing the problem is c.getComName:

这是我在前端用于读取数据并将其存储在 JavaScript 对象中的代码。我不完全确定我需要逃到哪里。导致问题的字段是 c.getComName:

communications[<%=i%>][1] = new CommObject('<%=c.getComId()%>', '<%=c.getComName()%>');

UPDATED WITH HTML GENERATED:

更新生成的 HTML:

communications[0][1] = new CommObject('101', 'Caroline's Message');

采纳答案by Kevin Hakanson

Use the Apache StringEscapeUtils.escapeJavaScriptfunction.

使用 Apache StringEscapeUtils.escapeJavaScript函数。

Escapes the characters in a String using JavaScript String rules.

Escapes any values it finds into their JavaScript String form.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

So a tab becomes the characters '\' and 't'.
Escapes the characters in a String using JavaScript String rules.

Escapes any values it finds into their JavaScript String form.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

So a tab becomes the characters '\' and 't'.

回答by OscarRyz

That's strange.

真奇怪。

What about:

关于什么:

'<%=c.getComName().replaceAll("\'","\\'")%>'

If that works, you just have to figure out how to add the \".

如果可行,您只需要弄清楚如何添加\"。

回答by amischiefr

When you return the HTML from the CommObject class add in the \" instead of the ' and before the name (e.g. Caroline's message)

当您从 CommObject 类返回 HTML 时,在名称前添加 \" 而不是 '(例如 Caroline 的消息)

Like this: return "\"" + comName + "\"";

像这样: return "\"" + comName + "\"";

回答by RHSeeger

I prefer to avoid scriptlets in the middle of my page and was having to use them (increasingly often) to escape strings when used in JavaScript code. I wanted an Expression Language(EL) way of escaping the strings. I created a very small custom taglib that I use for just this purpose:

我更喜欢避免在我的页面中间使用 scriptlet,并且在 JavaScript 代码中使用它们时不得不(越来越频繁地)使用它们来转义字符串。我想要一种转义字符串的表达式语言(EL) 方式。我创建了一个非常小的自定义标签库,我仅用于此目的:

Utilities.java:

实用程序.java:

package com.mycom.taglibs;

import org.apache.commons.lang.StringEscapeUtils;

public class Utilities {
    public static String escapeJS(String value) {
        return StringEscapeUtils.escapeJavaScript(value);
    }
}

mytaglib.tld:

mytaglib.tld:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">

  <description>My Tag Library</description>
  <display-name>Tag Utils</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>myt</short-name>

  <function>
    <description>
        JavaScript Escape function
    </description>
    <name>escapeJS</name>
    <function-class>com.mycom.taglibs.Utilities</function-class>
    <function-signature>java.lang.String escapeJS(java.lang.String)</function-signature>
  </function>
</taglib>

And, in the JSP page:

并且,在 JSP 页面中:

<%@ taglib prefix="myt" uri="/WEB-INF/mytaglib.tld" %>
The escaped string is: ${myt:escapeJS(variableHoldingTheString)}

回答by nickc

You could use JSP core tags:

您可以使用 JSP 核心标签:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>      
var jsVar = "<c:out value='${stringVariable}' />";

回答by boniezuvyz

You can use the JSTL escape function fn:escapeXml()to get rid of anomalies caused due to single quotes(`). The following example demonstrates the difference.

您可以使用 JSTL 转义函数fn:escapeXml()来摆脱由于单引号 (`) 引起的异常。以下示例演示了差异。

For example:

例如:

<c:set var="string1" value="This is abc's first String."/>
<c:set var="string2" value="This is abc's second String."/>

<p>With escapeXml() Function:</p>
<p>string (1): ${fn:escapeXml(string1)}</p>

<p>Without escapeXml() Function:</p>
<p>string (2): ${fn:escapeXml(string2)}</p>

RESULT

结果

string (1): This is abc s first String.

string (2): This is abc's second String.

string (1):这是 abc 的第一个 String。

字符串 (2):这是 abc 的第二个字符串。

回答by Radboud

fn:escapeXmldoes not work in JavaScript. It replaces 'with #&0039;still causing an error when the JavaScript is executed.

fn:escapeXml在 JavaScript 中不起作用。它取代'#&0039;被执行的JavaScript时仍然导致错误。

Only escaping in the JavaScript manner is correct: \'

只有以 JavaScript 方式转义才是正确的: \'

The Apache StringEscapeUtils.escapeJavaScript function does this for you. Creating a taglib for it greatly simplifies matters.

Apache StringEscapeUtils.escapeJavaScript 函数会为您完成这项工作。为它创建一个标签库大大简化了事情。

回答by Aleksey Shnepov

Also we have very nice solution from Spring:

我们也有来自 Spring 的非常好的解决方案:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<spring:message code="${propertyName}" javaScriptEscape="true"/>

So, issue from the question of this post can be resolved in this way:

所以,这篇文章的问题可以通过这种方式解决:

communications[<%=i%>][1] = new CommObject('<spring:message code="${c.comId}" javaScriptEscape="true"/>', '<spring:message code="${c.comName}" javaScriptEscape="true"/> <%=c.getComName()%>');