[英]How to get the the URI path for javax.ws.rs.core.UriInfo with parameters instead of values
[英]How to get relative path from UriInfo
我正在使用Java中的JAX-RS。 我需要從UriInfo獲取URI的相對路徑,即沒有方案和權限部分但具有路徑和查詢參數的URI。 最好的方法是什么?
根據https://jsr311.java.net/nonav/javadoc/javax/ws/rs/core/UriInfo.html如果您調用
getPath()
您將“獲取當前請求相對於基本URI的路徑作為字符串。”
盡管幾年后,我還是需要同樣的東西。 不過,這是怎么回事。
URI requestURI = this.uriInfo.getRequestUri();
URI baseUri = this.uriInfo.getBaseUri();
URI uri = baseUri.relativize(requestURI);
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);
檢查一下:
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.