Servlet請求轉發與重定向路徑問題!

WEB應用部署到Tomcat:java

<Context path="/project" docBase="D:\code_tower\code_tower\WebRoot" reloadable="true"/>

應用目錄結構:瀏覽器

start.jsp發起請求:服務器

    <form action="../../ts/TestServlet">
        <!-- action應相對於當前jsp文件位置 -->
        <input type="text" name="key" value="zhongbinhua"/>
        <input type="submit"/>
    </form>

result.jsp 請求轉發或從定向頁面:app

  <body> username:<%=request.getParameter("key") %>
  </body>

部署描述符中對Servlet配置:jsp

  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/ts/TestServlet</url-pattern>
  </servlet-mapping>

 Servlet示例:url

package com.test; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //請求轉發:共發送1個請求
        /**瀏覽器顯示:username:zhongbinhua */
        
        //瀏覽器地址:請求:http://localhost:8080/project/ts/TestServlet?key=zhongbinhua //200 OK //絕對路徑:'/'指http://localhost:8080/project
        RequestDispatcher dis = request.getRequestDispatcher("/result/result.jsp"); /**相對路徑:相對當前Servlet(TestServlet)的路徑*/
        //RequestDispatcher dis = request.getRequestDispatcher("../result/result.jsp");
 dis.forward(request, response); //重定向:共發送2個請求:服務器返回給瀏覽器第一個請求的響應以後,瀏覽器自動向服務器發送第二個請求!
        /**瀏覽器地址:http://localhost:8080/project/result/result.jsp*/
        /**瀏覽器顯示:username:null */
        
        //第一個請求正確:http://localhost:8080/project/ts/TestServlet?key=zhongbinhua
        /**第二個請求絕對路徑錯誤:http://localhost:8080/result/result.jsp * '/'指http://localhost:8080 */
        //response.sendRedirect("/result/result.jsp"); //第一個請求正確:http://localhost:8080/project/ts/TestServlet?key=zhongbinhua
        /**第二個請求相對路徑錯誤: * http://localhost:8080/project/ts/result/result.jsp */
        //response.sendRedirect("result/result.jsp"); //第一個請求正確:http://localhost:8080/project/ts/TestServlet?key=zhongbinhua //302 Moved Temporarily //http://localhost:8080/project/result/result.jsp //200 OK
        /**相對路徑:相對當前Servlet(TestServlet)的路徑*/
        //response.sendRedirect("../result/result.jsp");
 } }

 Servlet重定向示意圖: 共2個請求!spa

 

 Servlet請求轉發示意圖: 共1個請求!code

相關文章
相關標籤/搜索