Reputation: 9924
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
Upvotes: 2
Views: 942
Reputation: 70909
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("../..")
.`
Upvotes: 3