请求转发和重定向
请求转发
A向B请求资源,B没有该资源,于是B向C请求该资源。C将资源返回给B,B将资源返回给A。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Attribute涉及servlet之间的传参
request.setAttribute("name", "lsk");
// 将请求传递给s2,s2是xml文件中设置的另一个servlet的<url-pattern>
request.getRequestDispatcher("s2").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String u_name = (String)request.getAttribute("name");
response.getWriter().append("name:").append(u_name);
}
特点:参数共享,一次请求,地址不变
重定向
A向B请求资源,B没有该资源,B告诉A:C有你要的资源。于是A向C请求资源,C将资源返回给A。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 返回给请求方资源拥有者s2
response.sendRedirect("s2");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String u_name = (String)request.getAttribute("name");
response.getWriter().append("name:").append(u_name);
}
特点:参数不共享,两次请求,地址变化 。url地址会由s1转到s2
还没有评论,来说两句吧...