如何从UriInfo获得相对路径

时间:2014-06-19 07:17:05

标签: java path jax-rs

我在Java中使用JAX-RS。 我需要从UriInfo获取URI的相对路径,即没有方案和权限部分但带有路径和查询参数的URI。 最好的方法是什么?

4 个答案:

答案 0 :(得分:1)

根据https://jsr311.java.net/nonav/javadoc/javax/ws/rs/core/UriInfo.html,如果你打电话

 getPath() 

您将"以字符串形式获取当前请求相对于基URI的路径。"

答案 1 :(得分:1)

虽然几年后我需要完全相同的东西。不过这是怎么回事。

URI requestURI = this.uriInfo.getRequestUri();
URI baseUri = this.uriInfo.getBaseUri();
URI uri = baseUri.relativize(requestURI);

答案 2 :(得分:0)

String sourceUrl = "http://www.example.com/mysite/whatever/somefolder/bar/unsecure!+?#whätyöühäv€it/site.html"; // your current site
    String targetUrl = "http://www.example.com/mysite/whatever/otherfolder/other.html"; // the link target
    String expectedTarget = "../../../otherfolder/other.html";
    String[] sourceElements = sourceUrl.split("/");
    String[] targetElements = targetUrl.split("/"); // keep in mind that the arrays are of different length!
    StringBuilder uniquePart = new StringBuilder();
    StringBuilder relativePart = new StringBuilder();
    boolean stillSame = true;
    for(int ii = 0; ii < sourceElements.length || ii < targetElements.length; ii++) {
        if(ii < targetElements.length && ii < sourceElements.length && 
                stillSame && sourceElements[ii].equals(targetElements[ii]) && stillSame) continue;
        stillSame = false;
        if(targetElements.length > ii)
          uniquePart.append("/").append(targetElements[ii]);
        if(sourceElements.length > ii +1)
            relativePart.append("../");
    }

    String result = relativePart.toString().substring(0, relativePart.length() -1) + uniquePart.toString();
    System.out.println("result: " + result);

答案 3 :(得分:0)

检查一下:

String uri = "http://google.com/path?q1=va";
    int index = -1;
    if ((index = uri.indexOf("://")) > 0) {
        uri = uri.substring(index + 3);
    }
    index = uri.indexOf('/');
    uri = uri.substring(index);
    System.out.println(uri);

或者像这样:

    URI uri  = new URI("http://google.com/path?q1=va");
    System.out.println(uri.getPath()+"?"+uri.getQuery());