簡體   English   中英

使用Java將帶有相對URL的錨標記轉換為HTML內容中的絕對URL

[英]Converting anchor tag with relative URL to absolute URL in HTML content using Java

情況:

在服務器A上,我們要在服務器A上在線顯示來自服務器B的內容。

問題:

服務器B上的內容中的某些超鏈接是相對於服務器B的,這使得它們在服務器A上顯示時無效。

給定一段HTML代碼,其中包含如下所示的定位標記

<a href="/something/somwhere.html">Somewhere</a>

將它們轉換為最有效的方法是什么

<a href="http://server-b.com/something/somewhere.html">Somewhere</a>

內容中可以有多個錨標記,一個要注意的是某些標記可​​能是絕對的,我想保留這些標記,我只想在服務器B的域之前添加相對URL

根據周圍很多你的web應用程序的設置方式,以及您的有效定義的東西,這可能不是你所需要的或所期待的。 但無論如何,如果你有你的HTML作為一個字符串(在例如過濾器的一些晚期),你可以這樣做:

html = html.replaceAll("href=\"/", "href=\"http://server-b.com/")

有一種方法,我用它來將相對URL轉換為絕對URL。 我用它來將某些頁面轉換為電子郵件正文。

public String replaceLinks(String address, String content) throws URISyntaxException{
    //absolute URI used for change all relative links
    URI addressUri = new URI(address);
    //finds all link atributes (href, src, etc.)
    Pattern pattern = Pattern.compile("(href|src|action|background)=\"[^\"]*\"", Pattern.CASE_INSENSITIVE);
    Matcher m = pattern.matcher(content);
    //determines if the link is allready absolute
    Pattern absoluteLinkPattern = Pattern.compile("[a-z]+://.+");
    //buffer for result saving
    StringBuffer buffer = new StringBuffer();
    //position from where should next interation take content to append to buffer
    int lastEnd = 0;
    while(m.find()){
        //position of link in quotes
        int startPos = content.indexOf('"',m.start())+1;
        int endPos = m.end()-1;
        String link = content.substring(startPos,endPos);
        Matcher absoluteMatcher = absoluteLinkPattern.matcher(link);
        //is the link relative?
        if(!absoluteMatcher.find())
        {
            //create relative URL
            URI tmpUri = addressUri.resolve(link);
            //append the string between links
            buffer.append(content.substring(lastEnd,startPos-1));
            //append new link
            buffer.append(tmpUri.toString());
            lastEnd =endPos+1;
        }
    }
    //append the end of file
    buffer.append(content.substring(lastEnd));
    return buffer.toString();
}

希望能幫助到你。

我不會用Java做到這一點。 我喜歡在視圖層中處理特定於視圖的邏輯。 我假設此代碼塊來自AJAX調用。 因此,您可以做的是從AJAX調用中獲取HTML,然后執行以下操作:

jQuery(html).find("a[href]").each(function(index, value) {
  var $a = jQuery(value);
  var href = $a.attr("href");

  if(!/^http:/.test(href)) {
     $a.attr("href", "http://server-b.com" + href);
   }
});

或者,如果您真的想用Java做到這一點,Lauri的答案將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM