Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Encoding ampersands in a URL  RSS feed

 
Andy Deighton
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my webapp, I need to post a URL that contains values containing ampersands. However, ampersands in URLs get interpreted as parameter delimiters and this breaks my servlet code. E.g.
I need to pass:
http://blah/service/?name=hello&value=Gilbert & Sullivan
How do I get that ampersand in there without my browser turning into a "&" before posting the url? Do I have to wrap it in something?
Regards,
Andy
 
Chris Baron
Ranch Hand
Posts: 1061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Andy,
encode your urlquery-strings with javascript: escape( "Gilbert & Sullivan" );
and get it decoded in your servlet with java.net.URLDecoder
hth
 
Andy Deighton
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christian,
That seems like the right way, but I need to encode (escape) an HREF url that is built up from JSP elements:
http://blah/doIt/?param=<%=name%>&other=<%=composer%>
Trying to work out how to get the escape() method to answer a string which is then used in the href..
Andy
 
Andy Deighton
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christian, if it helps explain what I'm doing - here is the actual href:
<a href="javascript:escape('/ict_kb/search?action=showDetail®ion=<%=region%>&item=hotel&id=<%=hotel%>');"><%=hotel.getName()%></a>
This just answers a page showing the string produced by the escape() method. I can't remember how to get a javascript string into a url.. Any ideas?
Andy
 
Chris Baron
Ranch Hand
Posts: 1061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use java.net.URLEncoder

Note in "hotel" that since jdk1.4 you can specify the charset ( wärri useful )
 
Andy Deighton
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christian,
That solved it! Thank you VERY much. I should read the Javadoc a bit more from now on!!
Regards,
Andy
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!