19

In my web page when form is submitted witha space entered in text field, it is being read as %20 in backend java code instead of space. I can replace %20 back to "" in backend but i think it is not the right approach and it could happen anywhere in the application.

Is there any better way of handling it in front end when you submit form?

McQueen
  • 460
  • 2
  • 9
  • 20

3 Answers3

32

That's nothing wrong with that. It's how characters are escaped in a URL. You should use URLDecoder, which is particularly appropriate because, despite of its name, it does application/x-www-form-urlencoded decoding:

String decoded = URLDecoder.decode(queryString, "UTF-8");

Then you'll be able to build a map of key/value pairs parsing the query part of the URL, splitting on &, and using = to separate the key from the value (which may also be null).

However note that if the URL is passed as a URI object, it has a nice getQuery() which already returns the unescaped text.

If you use the servlet API, you don't have to escape anything because there are nice methods like getParameterMap().

Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • Likely the framework you use on the server side makes everything available under some *params* map. The UTF-8 in my example serves because the decoder must know the charset `%20` refers to. "*The current URL request is already UTF-8*" I don't know what it means exactly... – Raffaele Mar 05 '13 at 22:45
  • The request line (which contains the portion after the host) can only contain a subset of ASCII characters. Plus, some characters are special and must be escaped. In addition, every character outside of the whitelist, must be escaped using `%XX` - See [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt) – Raffaele Mar 05 '13 at 22:54
  • There ain't anything as a *UTF-8 charset*. There's the Unicode set, and UTF-8 is an encoding scheme. The Java API used in my answer requires the scheme to build characters from octets. – Raffaele Mar 05 '13 at 23:21
  • @Fonda - As a warning, your comments here got a little rude, so I removed them. Raffaele is just trying to help you by providing an answer to your question. – Brad Larson Mar 06 '13 at 22:16
  • Quick one! You can replace `"UTF-8"` with `StandardCharsets.UTF_8` so you can avoid throwing an `UnsupportedEncodingException` error or even using try-catch – Waleed Abdalmajeed Oct 25 '20 at 10:32
12

You could pass it through a the URLDecoder, that way your are not just sorting the problem for %20 but other URLEncoded values http://docs.oracle.com/javase/7/docs/api/java/net/URLDecoder.html

Kevin D
  • 3,564
  • 1
  • 21
  • 38
7
 try {
         String result = URLDecoder.decode(urlString, "UTF-8");
     } catch (UnsupportedEncodingException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
Hsm
  • 1,510
  • 17
  • 16