tags:

views:

1391

answers:

3

I need to split out parameters given a URL string.

I got the url value using request.getHeader("Referer") e.g.:

string rr=request.getHeader("Referer");
<%= rr %>

i got the url as http://www.sun.com/questions?uid=21&amp;value=gg

Now I stored that url in as string how do I get the value parameter value as uid=21 and value=gg

Please respond me

thanks in advance prakash

+2  A: 

You need to:

  1. take the string after the '?'
  2. split that on '&' (you can do this and the above by using the URL object and calling getQuery())
  3. You'll then have strings of the form 'x=y'. Split on the first '='
  4. URLDecode the result parameter values.

This is all a bit messy, unfortunately.

Why the URLDecode step ? Because the URL will be encoded such that '=' and '?' in parameter values won't confuse a parser.

Brian Agnew
getParameter will yield results from the **current** URL, not from the REFERER URL.
Arjan
Doh. Well spotted and changed approriately
Brian Agnew
+2  A: 

This tutorial might help a bit.

What you need to do is parse the URL, then get the 'query' property, then parse it into name/value pairs.

So something like this:

URL url = new URL(referer);
String queryStr = url.getQuery();

String[] params = queryStr.split("&");
for (String param: params) {
    String key = param.substring(0, param.indexOf('=');
    String val = param.substring(param.indexOf('=') + 1);
}

Disclaimer: this has not been tested, and you will need to do more error checking!

Phill Sacre
Won't this have difficulty with URL-encoded parameters ?
Brian Agnew
Good catch - you'd probably need to decode using URLDecoder.decode(...)
Phill Sacre
As for the error checking: not each parameter needs a value. (Which is not really an error, but needs to be taken care of as then the '=' may be missing.)
Arjan
@Phill Sacre - it is usually preferable to use the `URI` class in preference to `URL`.
McDowell
A: 
Joe23