Java 如何使用;申请书;Servlet中的对象?
如果我们正在编写一个JSP文件,我们只需要使用嵌入的“应用程序”对象。但是如何在Servlet中使用它呢?对象引用,您应该能够在Servlet中引用它 要引用ServletContext,您需要执行以下操作:Java 如何使用;申请书;Servlet中的对象?,java,jsp,servlets,Java,Jsp,Servlets,如果我们正在编写一个JSP文件,我们只需要使用嵌入的“应用程序”对象。但是如何在Servlet中使用它呢?对象引用,您应该能够在Servlet中引用它 要引用ServletContext,您需要执行以下操作: // Get the ServletContext ServletConfig config = getServletConfig(); ServletContext sc = config.getServletContext(); 从那时起,您将以与JSP中使用应用程序对象相同的方式使
// Get the ServletContext
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
从那时起,您将以与JSP中使用应用程序对象相同的方式使用sc对象。尝试以下方法:
ServletContext application = getServletConfig().getServletContext();
JSP中的
应用程序
对象称为servlet中的对象。这可以通过继承的方法获得。除了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();
// ...
}
}
另请参见。在Java web应用程序中,您通常拥有
请求
对象。因此,您可以获得如下所示的“应用程序”
对象:
request.getServletContext().getServerInfo()