Search code examples
javajavascriptjspencodingstruts

script construction is not proper if the name has special symbols


I am getting user name from the server side and showing it in the jsp as follows

String userName = getFullName();
request.setAttribute("userName",userName);

Jsp file

<div onclick=callToDoScript('<c:out value="${userName}"/>')> </div>

This is working fine. In my case the user name might contain japanese characters, single quotes, bracket or any other special characters.

The script construction is broken badly if the user name contains single quotes like below

<div onclick=callToDoScript('rock's"name')> </div>

If i encode the name japanese letters are not displayed property.

I need to know the list of scenarios that may break the construction and the solution for the same

Thanks in advance.


Solution

  • After doing some search I have found the solution for my issue.

    String userName = getFullName();
    userName = StringEscapeUtils.escapeEcmaScript(userName);
    request.setAttribute("userName",userName);