如果我们正在编写 JSP 文件,则只需使用嵌入的“应用程序”对象。但如何在 Servlet 中使用它呢?
The application
JSP 中的对象称为ServletContext https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.htmlServlet 中的对象。这可以通过继承获得GenericServlet#getServletContext() https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--方法。您可以在 servlet 中的任何位置调用它,除了init(ServletConfig)
method.
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();
// ...
}
}
也可以看看获取 Servlet Context 的不同方法 https://stackoverflow.com/questions/35837285/differents-ways-to-get-servlet-context.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)