Reputation: 490
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?
Upvotes: 20
Views: 65604
Reputation: 1540
try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 8
Reputation: 20875
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()
.
Upvotes: 34
Reputation: 3594
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
Upvotes: 12