Solved

Displaying single quotes in textarea / textbox

Posted on 2003-10-28
10
4,129 Views
Last Modified: 2008-01-16
Hi all,

Currently, I have a code to handle single and double quotes from the user input. I traverse the string provided by the user input and replace the quotes ' and " with the HTML ASCII equivalent as follows in a java class:

//textProcess method in PM.class
public String textProcess (String s) throws ClassNotFoundException, SQLException{
            StringBuffer newString= new StringBuffer("");
            char ch;
            int i;
            
            for( i=0; i <s.length(); i++ ){
                  ch = s.charAt(i);
                  switch(ch) {
                        case '\'': newString.append("&#39"); break;
                        case '"': newString.append("&#34"); break;
                        default: newString.append(ch); break;
                  }//end switch      
            }//end for
            
            return newString.toString();
}//end textProcess


In my JSP, when I use the out.println() method to print the string returned by the textProcess method above, it prints out the quotes as they are perfectly.

However, I can't display the returned string in my textbox/textarea value.

String myStringThatContainsQuotes = PM.textProcess(userInput);
<INPUT TYPE='TEXT' VALUE='<%= myStringThatContainsQuotes%>'>

The string displayed in my textbox gets truncated after it detected a single quote in the variable "myStringThatContainsQuotes".

I thought I had already replaced all single quote and double quotes with the HTML ASCII code? How did this happen? Can anyone provide some advice to solve this problem?

Thanks loads!
0
Comment
Question by:capricious
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +3
10 Comments
 
LVL 6

Expert Comment

by:kotan
ID: 9639997
<INPUT TYPE='TEXT' VALUE='<%= myStringThatContainsQuotes%>'>

change to

<INPUT TYPE="TEXT" VALUE="<%= myStringThatContainsQuotes%>">
0
 

Author Comment

by:capricious
ID: 9640032
Hi, thanks for your reply.

But if myStringThatContainsQuotes contains double quotes, the same problem exists.

How may I rectify it?
0
 
LVL 1

Expert Comment

by:deepak_a
ID: 9640667
<INPUT TYPE="TEXT" VALUE="<%= myStringThatContainsQuotes%>">

A small change
in ur method, on top declare
String str = "";

And in this part of ur switch - case make the change

case '"':
str += '\\';
str += "\"";
newString.append( str ); break;

I bet u will win with this one.


0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:Xyleen
ID: 9640883
i also think you're function isn't really working and doesn't replace it.

I use these functions :


   // see http://hotwired.lycos.com/webmonkey/reference/special_characters/
      static Object[][] entities = {
          {"#39", new Integer(39)},       // ' - apostrophe
          {"quot", new Integer(34)},      // " - double-quote
          {"amp", new Integer(38)},       // & - ampersand
          {"lt", new Integer(60)},        // < - less-than
          {"gt", new Integer(62)},        // > - greater-than
          {"nbsp", new Integer(160)},     // non-breaking space
          {"copy", new Integer(169)},     // © - copyright
          {"reg", new Integer(174)},      // ® - registered trademark
          {"Agrave", new Integer(192)},   // À - uppercase A, grave accent
          {"Aacute", new Integer(193)},   // Á - uppercase A, acute accent
          {"Acirc", new Integer(194)},    // Â - uppercase A, circumflex accent
          {"Atilde", new Integer(195)},   // Ã - uppercase A, tilde
          {"Auml", new Integer(196)},     // Ä - uppercase A, umlaut
          {"Aring", new Integer(197)},    // Å - uppercase A, ring
          {"AElig", new Integer(198)},    // Æ - uppercase AE
          {"Ccedil", new Integer(199)},   // Ç - uppercase C, cedilla
          {"Egrave", new Integer(200)},   // È - uppercase E, grave accent
          {"Eacute", new Integer(201)},   // É - uppercase E, acute accent
          {"Ecirc", new Integer(202)},    // Ê - uppercase E, circumflex accent
          {"Euml", new Integer(203)},     // Ë - uppercase E, umlaut
          {"Igrave", new Integer(204)},   // Ì - uppercase I, grave accent
          {"Iacute", new Integer(205)},   // Í - uppercase I, acute accent
          {"Icirc", new Integer(206)},    // Î - uppercase I, circumflex accent
          {"Iuml", new Integer(207)},     // Ï - uppercase I, umlaut
          {"ETH", new Integer(208)},      // Ð - uppercase Eth, Icelandic
          {"Ntilde", new Integer(209)},   // Ñ - uppercase N, tilde
          {"Ograve", new Integer(210)},   // Ò - uppercase O, grave accent
          {"Oacute", new Integer(211)},   // Ó - uppercase O, acute accent
          {"Ocirc", new Integer(212)},    // Ô - uppercase O, circumflex accent
          {"Otilde", new Integer(213)},   // Õ - uppercase O, tilde
          {"Ouml", new Integer(214)},     // Ö - uppercase O, umlaut
          {"Oslash", new Integer(216)},   // Ø - uppercase O, slash
          {"Ugrave", new Integer(217)},   // Ù - uppercase U, grave accent
          {"Uacute", new Integer(218)},   // Ú - uppercase U, acute accent
          {"Ucirc", new Integer(219)},    // Û - uppercase U, circumflex accent
          {"Uuml", new Integer(220)},     // Ü - uppercase U, umlaut
          {"Yacute", new Integer(221)},   // Ý - uppercase Y, acute accent
          {"THORN", new Integer(222)},    // Þ - uppercase THORN, Icelandic
          {"szlig", new Integer(223)},    // ß - lowercase sharps, German
          {"agrave", new Integer(224)},   // à - lowercase a, grave accent
          {"aacute", new Integer(225)},   // á - lowercase a, acute accent
          {"acirc", new Integer(226)},    // â - lowercase a, circumflex accent
          {"atilde", new Integer(227)},   // ã - lowercase a, tilde
          {"auml", new Integer(228)},     // ä - lowercase a, umlaut
          {"aring", new Integer(229)},    // å - lowercase a, ring
          {"aelig", new Integer(230)},    // æ - lowercase ae
          {"ccedil", new Integer(231)},   // ç - lowercase c, cedilla
          {"egrave", new Integer(232)},   // è - lowercase e, grave accent
          {"eacute", new Integer(233)},   // é - lowercase e, acute accent
          {"ecirc", new Integer(234)},    // ê - lowercase e, circumflex accent
          {"euml", new Integer(235)},     // ë - lowercase e, umlaut
          {"igrave", new Integer(236)},   // ì - lowercase i, grave accent
          {"iacute", new Integer(237)},   // í - lowercase i, acute accent
          {"icirc", new Integer(238)},    // î - lowercase i, circumflex accent
          {"iuml", new Integer(239)},     // ï - lowercase i, umlaut
          {"igrave", new Integer(236)},   // ì - lowercase i, grave accent
          {"iacute", new Integer(237)},   // í - lowercase i, acute accent
          {"icirc", new Integer(238)},    // î - lowercase i, circumflex accent
          {"iuml", new Integer(239)},     // ï - lowercase i, umlaut
          {"eth", new Integer(240)},      // ð - lowercase eth, Icelandic
          {"ntilde", new Integer(241)},   // ñ - lowercase n, tilde
          {"ograve", new Integer(242)},   // ò - lowercase o, grave accent
          {"oacute", new Integer(243)},   // ó - lowercase o, acute accent
          {"ocirc", new Integer(244)},    // ô - lowercase o, circumflex accent
          {"otilde", new Integer(245)},   // õ - lowercase o, tilde
          {"ouml", new Integer(246)},     // ö - lowercase o, umlaut
          {"oslash", new Integer(248)},   // ø - lowercase o, slash
          {"ugrave", new Integer(249)},   // ù - lowercase u, grave accent
          {"uacute", new Integer(250)},   // ú - lowercase u, acute accent
          {"ucirc", new Integer(251)},    // û - lowercase u, circumflex accent
          {"uuml", new Integer(252)},     // ü - lowercase u, umlaut
          {"yacute", new Integer(253)},   // ý - lowercase y, acute accent
          {"thorn", new Integer(254)},    // þ - lowercase thorn, Icelandic
          {"yuml", new Integer(255)},     // ÿ - lowercase y, umlaut
          {"euro", new Integer(8364)},    // Euro symbol
      };
      static Map e2i = new HashMap();
      static Map i2e = new HashMap();
      static {
          for (int i=0; i<entities.length; ++i) {
              e2i.put(entities[i][0], entities[i][1]);
              i2e.put(entities[i][1], entities[i][0]);
          }
      }

      /**
       * Turns funky characters into HTML entity equivalents<p>
       * e.g. <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>.
       * Update: supports nearly all HTML entities, including funky accents. See the source code for more detail.
       * @see #htmlunescape(String)
       **/
      public static String htmlescape(String s1)
      {
          StringBuffer buf = new StringBuffer();
          int i;
          for (i=0; i<s1.length(); ++i) {
              char ch = s1.charAt(i);
              String entity = (String)i2e.get( new Integer((int)ch) );
              if (entity == null) {
                  if (((int)ch) > 128) {
                      buf.append("&#" + ((int)ch) + ";");
                  }
                  else {
                      buf.append(ch);
                  }
              }
              else {
                  buf.append("&" + entity + ";");
              }
          }
          return buf.toString();
      }

      /**
       * Given a string containing entity escapes, returns a string
       * containing the actual Unicode characters corresponding to the
       * escapes.
       *
       * Note: nasty bug fixed by Helge Tesgaard (and, in parallel, by
       * Alex, but Helge deserves major props for emailing me the fix).
       * 15-Feb-2002 Another bug fixed by Sean Brown <sean@boohai.com>
       *
       * @see #htmlescape(String)
       **/
      public static String htmlunescape(String s1) {
          StringBuffer buf = new StringBuffer();
          int i;
          for (i=0; i<s1.length(); ++i) {
              char ch = s1.charAt(i);
              if (ch == '&') {
                  int semi = s1.indexOf(';', i+1);
                  if (semi == -1) {
                      buf.append(ch);
                      continue;
                  }
                  String entity = s1.substring(i+1, semi);
                  Integer iso;
                  if (entity.charAt(0) == '#') {
                      iso = new Integer(entity.substring(1));
                  }
                  else {
                      iso = (Integer)e2i.get(entity);
                  }
                  if (iso == null) {
                      buf.append("&" + entity + ";");
                  }
                  else {
                      buf.append((char)(iso.intValue()));
                  }
                  i = semi;
              }
              else {
                  buf.append(ch);
              }
          }
          return buf.toString();
      }
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 9644204
in addition to all posted above, I sometimes also use javascrip/java encode and decode.
here is an example that contains two(2) solutions to your problem.
1. use text2html function which is close to what you are doing.
2. use javascript/jave encode/decode:

<%!
   public static String text2html(String s, boolean preformat)
   {
       StringBuffer buf = new StringBuffer();
       for (int i=0, limit=s.length(); i<limit; i++) {
           char c = s.charAt(i);
           switch( c ) {
               case ' ': if( preformat) buf.append( "&nbsp;" ); break;
               case '<': buf.append( "&lt;" ); break;
               case '>': buf.append( "&gt;" ); break;
               case '&': buf.append( "&amp;" ); break;
               case '\'': buf.append( "&#39;" ); break;
               case '"': buf.append( "&quot;" ); break;
               case '\n': if( preformat) buf.append( "<br>" ); break;
               default: buf.append( c );
           }
      }
      return buf.toString();
   }
%>
<% String xxx="myStr\"ingTh<atCo'ntai>nsQ+u otes"; %>
<FORM NAME=abc>
<html:submit property="abc">here it is</html:submit>
<INPUT TYPE="TEXT" NAME="field1" VALUE="">
<INPUT TYPE="TEXT" NAME="field2" VALUE="<%=text2html(xxx, false)%>">
</FORM>
<script>
      abc.field1.value=unescape('<%=java.net.URLEncoder.encode(xxx).replace( '+', ' ')%>' );
</script>
0
 
LVL 14

Accepted Solution

by:
kennethxu earned 50 total points
ID: 9644448
Revised and more complete example:
<%!
   public static String text2html(String s, boolean preformat)
   {
       StringBuffer buf = new StringBuffer();
       for (int i=0, limit=s.length(); i<limit; i++) {
           char c = s.charAt(i);
           switch( c ) {
               case '<': buf.append( "&lt;" ); break;
               case '>': buf.append( "&gt;" ); break;
               case '&': buf.append( "&amp;" ); break;
               case '\'': buf.append( "&#39;" ); break;
               case '"': buf.append( "&quot;" ); break;
               case ' ': if(preformat) buf.append( "&nbsp;" ); else buf.append( c ); break;
               case '\n': if(preformat) buf.append( "<br>" ); else buf.append( c ); break;
               default: buf.append( c );
           }
      }
      return buf.toString();
   }
%>
<% String xxx="my+String That<Contains>\"Quotes'"; %>
<% String yyy="my+String That<Contains>\"Quotes'\nand      CRLF"; %>
<FORM NAME=abc>
<h2>Use java.net.URLEncode and javascrpt:unescape():</h2>
<INPUT TYPE="TEXT" SIZE=50 NAME="text1" VALUE=""><br>
<TEXTAREA COLS=50 ROWS=4 NAME="textarea1"></TEXTAREA><br>

<h2>Use text2html()</h2>
<INPUT TYPE="TEXT" SIZE=50 NAME="text2" VALUE="<%=text2html(xxx, false)%>"><br>
<TEXTAREA COLS=50 ROWS=4 NAME="textarea2"><%=text2html(yyy, false)%></TEXTAREA><p>

<h3>preformat=false:</h3>
<%=text2html(yyy, false)%><p>

<h3>preformat=true:</h3>
<%=text2html(yyy, true)%><br>
</FORM>

<script>
      abc.text1.value=unescape('<%=java.net.URLEncoder.encode(xxx).replace( '+', ' ')%>' );
      abc.textarea1.value=unescape('<%=java.net.URLEncoder.encode(yyy).replace( '+', ' ')%>' );
</script>
0
 
LVL 3

Expert Comment

by:applekanna
ID: 9655641
Why are you replacing single ' with dounle ".

IS it for the SQL statments. if so there is an another soultion

to care of SQL statmets in JAVA, you can use a prepared statments , it wil make life a lot easier, lot lot easier.

here a link

http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_11962678.html
0
 
LVL 3

Expert Comment

by:applekanna
ID: 9655647
This will take care of your backend problem (if that was y u wanted to relace) and you need not worrry abt the fron end problem as it will take care of itself. Hope this helps.!

Cheers!
0
 

Author Comment

by:capricious
ID: 10751413
Hi guys,
Sorry for not returning back to the question, until I got a "warning" in my email. My bad.
Thanks for ALL the help rendered though!

capricious.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After seeing many questions for JRNL_WRAP_ERROR for replication failure, I thought it would be useful to write this article.
Make the most of your online learning experience.
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question