2

I would like to create a servlet filter to calculate the releative url path to root servlet for any given servlet request.

So for a servlet that is bound to http://somedomain/context/:

A request to http://somedomain/context/path1/path2 would return ..

and a request to http://somedomain/context/path1/path2/path3 would return ../..

Does any one know of a reliable way to do this?

TIA

BillMan
  • 9,434
  • 9
  • 32
  • 52
  • 3
    Why can't you just return `/context` always? – adarshr Jun 01 '12 at 14:20
  • I was using relative URLs for all my other links, and I was thinking that I would like to remain consistent here. I could be wrong, but that was my thinking. – BillMan Jun 01 '12 at 14:24
  • 2
    Don't use relative links. Not the `../`, `../..` types at least. Always construct the full URL. But be sure to fetch the context dynamically rather than hardcoding it. – adarshr Jun 01 '12 at 14:26
  • @sdarshr. Curious, why shouldn't I use .. or ../..? – BillMan Jun 01 '12 at 14:30
  • 1
    Just makes it cumbersome to manage as you go deeper. And you'll then have to think of asking questions like this one :) – adarshr Jun 01 '12 at 14:33
  • @BillMan traversing back using `/root` is simplest over using `parent/parent/parent`, when you already know what and where the root is. – Ravinder Reddy Jun 01 '12 at 14:33
  • @BillMan - To cheer you up, [Edwin Buck's answer is there](http://stackoverflow.com/a/10852242/767881). :) – Ravinder Reddy Jun 01 '12 at 14:38
  • Thanks guys, the worst programs start with bad assumptions :) – BillMan Jun 01 '12 at 14:47
  • Related: http://stackoverflow.com/questions/3655316/browser-cant-access-css-and-images-when-calling-a-servlet-which-forwards-to-a-j – BalusC Jun 05 '12 at 16:35

1 Answers1

3

With the new java filesystem utilities (1.7) the Path relativize(Path) method should work. From the Path Operations Tutorial.


Path p1 = Paths.get("joe");
Path p2 = Paths.get("sally");

In the absence of any other information, it is assumed that joe and sally are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally, you would expect to first navigate one level up to the parent node and then down to sally:

// Result is ../sally
Path p1_to_p2 = p1.relativize(p2);
// Result is ../joe
Path p2_to_p1 = p2.relativize(p1);

Now, whether such a technique is desirable, I'll leave that to others to comment.

Note that the paths do not need to exist on disk, and you can also declare a Path with a fixed root, so a Path like new Path("/servlet/subdir/subdir2") and a Path like new Path("/servlet") should relativize(...) to a Path like new Path("../..").`

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138