如果我们编写JSP文件,我们只需要使用嵌入的"应用程序"对象.但是如何在Servlet中使用它?
在applicationJSP中的对象被称为ServletContext在servlet对象.这可以通过继承的GenericServlet#getServletContext()方法获得.除了init(ServletConfig)方法之外,您可以在servlet中的任何位置调用它.
public class YourServlet extends HttpServlet {
@Override
public void init() throws ServletException {
ServletContext ctx = getServletContext();
// ...
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
另请参阅获取Servlet上下文的不同方法.