5.1什么是Context
- 文本上下文(官方定义)
- 具有超长的生存周期,随服务器而存在
5.2获取Context
ServletContext con = this.getServletContext();
5.3应用
1.传递变量
因为其超长的生存周期,可以用来储存一些公共变量,还可以传递变量
context1
public class Context1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext con = this.getServletContext();
con.setAttribute("username","root");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("already save username");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
context2
public class Context2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
ServletContext con = this.getServletContext();
String name = (String) con.getAttribute("username");
resp.getWriter().print("username = "+name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
访问结果
2.请求转发
将Context1修改为如下
public class Context1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext con = this.getServletContext();
con.setAttribute("username","root");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("already save username");
RequestDispatcher Rd = con.getRequestDispatcher("/Context2");
Rd.forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
则访问Context1结果如下