WEB应用部署到Tomcat:
<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 请求转发或从定向页面:
<body> username:<%=request.getParameter("key") %>
</body>
部署描述符中对Servlet配置:
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/ts/TestServlet</url-pattern>
</servlet-mapping>
Servlet示例:
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个请求!
Servlet请求转发示意图: 共1个请求!