[英]How to use the “application” object in a Servlet?
If we are coding a JSP file, we just need to use the embedded "application" object. 如果我们编写JSP文件,我们只需要使用嵌入的“应用程序”对象。 But how to use it in a Servlet? 但是如何在Servlet中使用它?
The application
object in JSP is called the ServletContext
object in a servlet. JSP中的application
对象称为servlet中的ServletContext
对象。 This is available by the inherited GenericServlet#getServletContext()
method. 这可以通过继承的GenericServlet#getServletContext()
方法获得。 You can call this anywhere in your servlet except of the init(ServletConfig)
method. 除了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();
// ...
}
}
See also Different ways to get Servlet Context . 另请参阅获取Servlet上下文的不同方法 。
The application object references javax.servlet.ServletContext and you should be able to reference that in your servlets. 应用程序对象引用javax.servlet.ServletContext ,您应该能够在servlet中引用它。
To reference the ServletContext you will need to do the following: 要引用ServletContext,您需要执行以下操作:
// Get the ServletContext
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
From then on you would use the sc object in the same way you would use the application object in your JSPs. 从那时起,您将使用sc对象,就像在JSP中使用应用程序对象一样。
尝试这个:
ServletContext application = getServletConfig().getServletContext();
In a Java web application you often have the request
object. 在Java Web应用程序中,您经常拥有request
对象。 So you can get the "application"
object like this: 所以你可以得到这样的"application"
对象:
request.getServletContext().getServerInfo()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.