pageContext, request,session,application 对象都有这些方法,称为域对象
Object getAttribute(String name)
Enumeration getAttributeNames()
removeAttribute(String name)
void setAttribute(String name,Object o)
pageContext:属性的作用范围仅限于当前JSP页面
request:仅限于同一个请求
session:限于一次会话(浏览器打开直到关闭是一次会话)
application:属性的作用范围限于当前web应用。只要在一处设置属性,在其他各处的JSP或Servlet中都可以获取到
请求的转发和重定向:
1.区别:请求的转发只发出了一次请求,而重定向则发出了两次请求
//转发:地址栏为/forwardServlet
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/forwardServlet")
public class ForwardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
//请求的转发
//1.调用HttpServletRequest的getRequestDispatcher()方法获取RequestDispatcher对象
//调用getRequestDispatcher()需要传入要转发的地址
String path = "testServlet";
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/" + path);
//2.调用HttpServletRequest的forward(request,response)进行请求的转发
requestDispatcher.forward(request, response);
}
}
//重定向:地址栏为testServlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/redirectServlet")
public class RedirectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
//执行请求的重定向,直接调用response.sendRedirect(path)方法,path为重定向的地址
String path = "testServlet";
response.sendRedirect(path);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
在最终的Servlet中,转发的request对象和中转的那个request是同一个对象,重定向的则不是。
转发:/ 代表的是当前web应用的根目录;重定向:代表的是当前web站点的根目录