sparkjava : problems passing urls as parameter to routes

With sparkjava you can build a helloworld website within lessthan a minute like Node Express (http://expressjs.com/).

Passing url parameters :
Consider creating a route like: http://host:port/url ( e.g. http://localhost:4567/https://finance.yahoo.com/q/ks?s=VNJTX+Key+Statistics )
whereas the black url portion you want to pass as parameter.
This can be done very easily using splats (http://sparkjava.com/documentation.html).
With the following code in your route:
  1. port(8081);//lets start our server on port 8081
  2. get("/", (request, response) -> "Welcome to HelloWorld Server! :)");
  3. get("/*", (request, response) -> {
  4.     String url = request.splat()[0];//take the first splat param value
  5.     return "Requested url : " + url;
  6.     });
And here the problem comes:
It prints:
  1. Requested url : https:/finance.yahoo.com/q/ks
The first thing is that it has removed the query string.
On top of that https:/finance.yahoo.com/q/ks
is not a valid url.

To solve this:

We can simply do some manipulate on the urls ourselves:
Corrected codes:
  1. get("/*", (request, response) -> {
  2.     String url = request.splat()[0];//take the first splat param value
  3.     url = manipulateUrl(url, request.queryString());
  4.     return "Requested url : " + url;
  5.     });
  6. //let's modify url param
  7. public static String manipulateUrl(String urlStr, String queryStr) throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {
  8.     urlStr = urlStr.replaceFirst("/", "//");
  9.     if (queryStr.length() >= 0) {
  10.         urlStr = urlStr + "?" + queryStr;
  11.     }
  12.     return urlStr;
  13.     }

No comments:

Post a Comment