RequestURI、ServletPath、ContextPath和轉發重定向的參數

一、requestURI、servletPath、contextPath

假設:

  • 當前的項目根目錄爲:/demo,即訪問首頁的路徑爲http://localhost:8080/demo/index.jsp
  • 頁面全部位於 web 根目錄下。

假設有一個 Servlet:

public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.service(request, response);
        System.out.println("context-path=" + request.getContextPath());
        System.out.println("servlet-path=" + request.getServletPath());
        System.out.println("request-uri=" + request.getRequestURI());
    }
}

那麼訪問首頁 http://localhost:8080/demo/index.jsp則會輸出:

context-path=/demo
servlet-path=/index.jsp
request-uri=/demo/index.jsp

二、轉發、重定向的參數

假設當前 Servlet 正在處理的請求的請求路徑爲/demo/control/login

/轉發

假設轉發的方式爲:

request.getRequestDispatcher("/home.jsp").forward(request, response);

那麼轉發到的路徑爲:

  • http://localhost:8080/demo/home.jsp
  • 相對 web 根目錄轉發。符合期望。

不帶/轉發

假設轉發的方式爲:

request.getRequestDispatcher("home.jsp").forward(request, response);

那麼轉發到的路徑爲:

  • http://localhost:8080/demo/control/home.jsp

  • 相對當前請求路徑轉發。不符合期望。

/重定向

假設重定向的方式爲:

response.sendRedirect("/login.jsp");

那麼重定向的路徑爲:

  • http://localhost:8080/login.jsp
  • 相對項目路徑(或 context-path)重定向。不符合期望。

不帶/重定向

假設重定向的方式爲:

response.sendRedirect("login.jsp");

那麼重定向的路徑爲:

  • http://localhost:8080/demo/control/login.jsp
  • 相對當前請求路徑轉發。不符合期望。

URL地址重定向

假設重定向的方式爲:

response.sendRedirect("https://www.google.com/");

那麼重定向的地址爲:

  • https://www.google.com/
  • 符合期望

統一格式化

可以定義一個方法來統一處理:

    public static void formatResponse(HttpServletRequest request,
                                      HttpServletResponse response, 
                                      String target,
                                      String responseMethod) throws ServletException, IOException {
        switch (responseMethod) {
            case "FORWARD": {
                String url = ("/" + target).replaceAll("/+", "/");
                request.getRequestDispatcher(url).forward(request, response);
            }
            case "REDIRECT": {
                String url;
                if (target.startsWith("http") || target.startsWith("www.")) {
                    url = target;
                } else {
                    url = ("/" + request.getContextPath() + "/" + target).replaceAll("/+", "/");
                }
                response.sendRedirect(url);
                break;
            }
            default: {

            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章