javascriptjavajspstringescapeutils

StringEscapeUtils.escapeJavaScript Escape Single Quote


I have 2 types of text string that I need to escape:

1) name=ALICE " (double quote)

2) name=ALICE ' (single quote)

This is my codes:

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

}

The solution works correctly for both ( able to save both name texts in database)

1) details-doublequote.jsp

2) details-singlequote.jsp

However, the display is a bit off. How can I hide the backslash character from showing when escaping the single quote? I want the jsp to display ALICE' instead if ALICE\' & ensure able to save the result in db


Solution

  • Problem fixed! Instead of putting the codes directly inside public ActionForward search (){}

    in the JSP file, assign decorator 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>
    

    in the decorator 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);