如何在 Glassfish V3 重寫/重定向 URL?

如何在 Glassfish V3 重寫/重定向 URL?

我想透過刪除檔案副檔名和縮短 URL 來簡化存取 Glassfish V3 應用程式的 URL。

我已經將我的應用程式設定為預設應用程序,因此無需在 URL 中包含上下文根。

我想:
* 刪除檔案副檔名
* 縮短資料夾結構深處檔案的 URL

我想使用模式匹配而不是基於每個文件來執行此操作(網站目前很小,但會經常更改並增長)。

我想做的一些例子:
* foo.com/bar.html -> foo.com/bar
* foo.com/folder1/folder2/bar2.html -> foo.com/bar2

任何幫助將不勝感激。謝謝。

乾杯,

答案1

取自http://www.sun.com/bigadmin/sundocs/articles/urlrdn.jsp看來這就是您正在尋找的。

網域內的 URL 重新導向

您可以使用redirect_屬性的url-prefix元素將URL轉送到同一網域中的另一個URL。

以下過程顯示如何使網站訪客能夠輸入http://www.mywebsite.com/myproduct1並被重新導向或轉送至http://www.mywebsite.com/mywarname/products/myproduct1.jsp

  1. 登入 Sun Java System Application Server 或 GlassFish 的管理控制台。
  2. 在管理控制台中,展開配置節點。
  3. 展開伺服器配置節點。

    如果您正在執行開發人員網域(不具有叢集功能的網域),請忽略此步驟。

  4. 展開 HTTP 服務。

  5. 展開虛擬伺服器。
  6. 按一下伺服器。
  7. 在編輯虛擬伺服器頁面上,按一下新增屬性按鈕。
  8. 在「名稱」欄中,鍵入redirect_1
  9. 如果您使用的是 Application Server 9.0,請from=/<context-root>/myproduct1 url-prefix=/mywarname/mypages/products/myproduct1.jsp在「值」欄位中鍵入。

    筆記- 您在此處提供的值<context-root>需要與 web.xml 或 application.xml 檔案中指定的上下文根的值相符。

    如果您使用的是 Application Server 9.1,請from=/myproduct1 url-prefix=/mywarname/mypages/products/myproduct1.jsp在「值」欄位中鍵入。

答案2

在這種情況下,您應該編寫一個 javax.servlet.Filter 實作來識別縮短的 URL 並將請求轉發到真正的目標。

/**
 *
 * @author vrg
 */
@WebFilter(filterName = "SimplifiedUrlRequestDispatcher", urlPatterns = {"/*"})
public class ShortenedUrlRequestDispatcher implements javax.servlet.Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //reading configuration from filterConfig
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String shortURI = httpRequest.getRequestURI();
        String realURI = getRealURI(shortURI);
        if (realURI == null) {
            //in this case the filter should be transparent
            chain.doFilter(request, response);
        } else {
            //forwarding request to the real URI:
            RequestDispatcher rd = request.getRequestDispatcher(realURI);
            rd.forward(request, response);
        }
    }
    /**
     * Calculates the real URI from the given URI if this is a shortened one,
     * otherwise returns null.
     * @param shortURI
     * @return 
     */
    private String getRealURI(String shortURI) {
        //TODO implement your own logic using regexp, or anything you like
        return null;
    }

    @Override
    public void destroy() {
    }

}

答案3

太棒了!優秀的入門讀物,但還有一件事 -RequestDispatcher rd = request.getRequestDispatcher(realURI);使用 servlet 路徑進行操作,獲取帶有應用程式名稱的 URI,它會給出錯誤。 so -req.getServletPath()給出了沒有上下文的正確路徑,並且調度程序按其應有的方式工作。

相關內容