Escape apostrophe as with c: out JSP

I have an object field with the name of the person.

If I use $ {person.lastName}, I get O'Brian

If i use

 <c:out value="${person.lastName}"/> 

I get OBrian

Both outputs break the following jsp code in IE

 <a href="#" 
    class="delete" 
    onclick="if(confirm('<c:out value="${application.lastName}"/> ' + _('Are you sure you want to delete this application?'))) {deleteApplication('${application.identifier}')};return false;"><bean:message key="application.delete"/></a>

because it is converted to

    onclick="if(confirm('O&#039;Brian '

or

    onclick="if(confirm('O'Brian '

I need O'Brian to be escaped as O \ 'Brian

Any idea how to solve this problem?

DECISION

Most elegant solutions seem to use a simple tag.

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

}

Then put the utils.tld file in WEB-INF:

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
    <tlibversion>1.2</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>bean</shortname><uri>utilsTags</uri>
    <uri>utilsTags</uri>
    <tag>
        <name>escapeJS</name>
        <tagclass>view.EscapeJS</tagclass>
        <bodycontent>scriptless</bodycontent>
        <attribute>
            <name>str</name>
            <required>true</required>       
            <rtexprvalue>true</rtexprvalue> 
        </attribute>                
    </tag>      
</taglib>

Then inside your jsp:

<%@ taglib prefix="utils" uri="utilsTags" %>

<utils:escapeJS str="${application.firstName}"/>
+3
source share
2 answers

You can define a new EL function that selects rows for you.

eg.

In java

public class MyStringUtil {
  public static String escapeJs( String str )
  {
    // escape the string (e.g. replace ' with \')
  }
}

In the tag library descriptor file:

<function>
 <name>escapeJs</name>
 <function-class>package.to.MyStringUtil</function-class>
 <function-signature>
   java.lang.String escapeJs( java.lang.String )
 </function-signature>
</function>

JSP ( .tld foo:

<a href="#" 
  class="delete" 
  onclick="if(confirm('${foo:escapeJs(person.lastName)}' + _('Are you sure you want to delete this application?'))) {deleteApplication('${application.identifier}')};return false;"><bean:message key="application.delete"/></a>
+3

O'brian , find, 'to \'

+1

Source: https://habr.com/ru/post/1710866/


All Articles