Escaping & in a URL
Asked Answered
C

4

10

I am using jsps and in my url I have a value for a variable like say "L & T". Now when I try to retrieve the value for it by using request.getParameter I get only "L". It recognizes "&" as a separator and thus it is not getting considered as a whole string.

How do I solve this problem?

Consueloconsuetude answered 4/2, 2010 at 7:21 Comment(0)
F
17
java.net.URLEncoder.encode("L & T", "utf8")

this outputs the URL-encoded, which is fine as a GET parameter:

L+%26+T
Figurate answered 4/2, 2010 at 7:25 Comment(0)
C
1

A literal ampersand in a URL should be encoded as: %26

// Your URL
http://www.example.com?a=l&t

// Encoded
http://www.example.com?a=l%26t
Categorical answered 4/2, 2010 at 7:26 Comment(0)
G
1

You need to "URL encode" the parameters to avoid this problem. The format of the URL query string is: ...?<name>=<value>&<name>=<value>&<etc> All <name>s and <value>s need to be URL encoded, which basically means transforming all the characters that could be interpreted wrongly (like the &) into %-escaped values. See this page for more information: http://www.w3schools.com/TAGS/ref_urlencode.asp

If you're generating the problem URL with Java, you use this method: String str = URLEncoder.encode(input, "UTF-8");

Generating the URL elsewhere (some templates or JS or raw markup), you need to fix the problem at the source.

Giffer answered 4/2, 2010 at 7:26 Comment(0)
E
0

You can use UriUtils#encode(String source, String encoding) from Spring Web. This utility class also provides means for encoding only some parts of the URL, like UriUtils#encodePath.

Elbring answered 23/11, 2017 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.