StringEscapeUtils.escapeJavaScript逃脱单引号

时间:2017-03-28 03:12:10

标签: javascript java jsp stringescapeutils

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

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

1 个答案:

答案 0 :(得分:0)

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

在JSP文件中,指定装饰器类

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

在装饰器类中, 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);