如何在 JSP 上转义撇号或引号(由 JavaScript 使用) [英] How to escape apostrophe or quotes on a JSP (used by JavaScript)

查看:41
本文介绍了如何在 JSP 上转义撇号或引号(由 JavaScript 使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

missing ) 在参数列表 'Caroline's message' 之后,

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

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

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

更新生成的 HTML:

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

解决方案

使用 Apache StringEscapeUtils.escapeJavaScript 函数.

<块引用>

使用 JavaScript 字符串规则对字符串中的字符进行转义.将它找到的任何值转义为其 JavaScript 字符串形式.正确处理引号和控制字符(制表符、反斜杠、cr、ff 等)所以制表符变成了字符 '\' 和 't'.

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:

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

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:

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

UPDATED WITH HTML GENERATED:

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

解决方案

Use the Apache StringEscapeUtils.escapeJavaScript function.

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'.

这篇关于如何在 JSP 上转义撇号或引号(由 JavaScript 使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆