StringEscapeUtils.escapeJavaScript 转义单引号

StringEscapeUtils.escapeJavaScript Escape Single Quote

我有两种类型的文本字符串需要转义:

1) name=ALICE "(双引号)

2) name=ALICE'(单引号)

这是我的代码:

if (name.indexOf('\'') >= 0){
        name=StringEscapeUtils.escapeJavaScript(name);
        System.out.println("escape by javascript " + name);

} else {
        name=StringEscapeUtils.escapeHtml(name);
        System.out.println("escape by html" + name);

}

解决方案对两者都有效(能够将两个名称文本保存在数据库中)

1) details-doublequote.jsp

2) details-singlequote.jsp

不过,显示有点不对劲。转义单引号时如何隐藏反斜杠字符不显示?我希望 jsp 显示 ALICE' 而不是 ALICE\' 并确保能够将结果保存在 db

问题已解决! 而不是直接把代码放在 public ActionForward search (){}

里面

在JSP文件中,分配装饰器class

<display:table sort="list" style="width: 100%" cellspacing="1" cellpadding="2" class="mydataTable" excludedParams="*" name="custTable" defaultsort="1" defaultorder="ascending" requestURI="<%=uri%>" pagesize="20" decorator="com.aza.util.MyDecorator">            
        <display:column style="width: 150px;" titleKey="customer.name" property="name" sortable="true" headerClass="sortable tabledisplay"/>    
    </display:table>

装饰器中class、MyDecorator.java

    MyModel cusModel = (MyModel) getCurrentRowObject();
    StringBuffer buf = new StringBuffer();

    String customerName=cusModel.getName();

    if (customerName.indexOf('\'') >= 0){
        customerName=StringEscapeUtils.escapeJavaScript(customerName);          
    } else {
        customerName=StringEscapeUtils.escapeHtml(customerName);            
    }

    cusModel.setName(customerName);