使用c:out JSP将撇号称为\’
我有一个带有人姓的对象字段。
如果我使用$ {person.lastName} ,我会得到奥布莱恩
如果我使用
我得到了奥布莱恩
两个输出都打破了IE中的下一个jsp代码
<a href="#" class="delete" onclick="if(confirm(' ' + _('Are you sure you want to delete this application?'))) {deleteApplication('${application.identifier}')};return false;">
因为它变成了
onclick="if(confirm('O'Brian '
要么
onclick="if(confirm('O'Brian '
我需要奥布莱恩作为奥布莱恩逃脱
知道如何解决这个问题吗?
解
最优雅的解决方案似乎使用简单的标签。
package view; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class EscapeJS extends SimpleTagSupport { public String str; public void doTag() throws JspException, IOException { getJspContext().getOut().print(str.replaceAll("\'", "\\\\'")); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } }
然后在WEB-INF中放入一个utils.tld文件:
1.2 1.1 beanutilsTags utilsTags escapeJS view.EscapeJS scriptless str true true
然后在你的jsp里面:
您可以定义一个新的EL函数,为您转义字符串。
例如
在Java中
public class MyStringUtil { public static String escapeJs( String str ) { // escape the string (eg replace ' with \') } }
在标记库描述符文件中:
escapeJs package.to.MyStringUtil java.lang.String escapeJs( java.lang.String )
然后在你的JSP中(假设你已经包含了前缀为foo
.tld
:
将它作为O’brian存储在数据库中,但在显示之前,请执行查找替换以将任何’转换为’