views:

1602

answers:

3

I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request.

It looks as if the javax.servlet.http.HttpUtils.parseQueryString method would be the obvious choice, but it has been deprecated.

Is there an alternative method that I am missing, or has it just been deprecated without an equivalent replacement/enhanced function?

+2  A: 

I think the idea is to use the HttpServletRequest instead. There is the getParameterMap(), getParameterNames() and getParameterValues() methods to start.

There is also the getParameter(String paramname) method to get the value of a specific method.

These make no distinction between querystring parameters and form parameters though so if your intention was to look for a querystring in aparticular then I guess this wouldn't help.

Vincent Ramdhanie
I probably should have been more specific in the question. I am attempting to parse a URL that is not the servlet request URL, but obtained as a parameter value(encoded URL) or string value from a database record.
Mads Hansen
A: 

As far as I know, there isn't one.

It shouldn't be too difficult to write one yourself though. The hardest part, I imagine, would be decoding the URL name/values (which really isn't that hard, if you think about it), and you can use java.net.URLDecoder#decodeURL(String,String) for that.

Jack Leow
+1  A: 

Well, as you mention that the URL does not come from a servlet request, the right answer is, as usual, it depends.

The problem with query part of an url is that there is no clear specification about how to handle parameters duplication.

For example, consider an url like this one:

http://www.example.com?param1=value1&param2=value2&param1=value3

What do you expect as a value for param1? the first value, the last one, an array? The issue is that, according to the specs, all these answers are valid and server vendor are free to support one of these or another. Some use the param1[] notation to indicate that it has to be treated as an array, but again, this is not a unified solution.

So the "best" solution is to know how your destination handle parameters, and mimic the behaviour with a self-made utility class.

gizmo
I don't think there's such dilemma, the obvious answer is the array.
Jaroslav Záruba
Well, according to the specs, it is not. I've worked on a project with Struts and Spring where only the last declaration was overriding the previous ones.
gizmo