[英]How to use the “application” object in a Servlet?
如果我們編寫JSP文件,我們只需要使用嵌入的“應用程序”對象。 但是如何在Servlet中使用它?
JSP中的application
對象稱為servlet中的ServletContext
對象。 這可以通過繼承的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();
// ...
}
}
另請參閱獲取Servlet上下文的不同方法 。
應用程序對象引用javax.servlet.ServletContext ,您應該能夠在servlet中引用它。
要引用ServletContext,您需要執行以下操作:
// Get the ServletContext
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
從那時起,您將使用sc對象,就像在JSP中使用應用程序對象一樣。
嘗試這個:
ServletContext application = getServletConfig().getServletContext();
在Java Web應用程序中,您經常擁有request
對象。 所以你可以得到這樣的"application"
對象:
request.getServletContext().getServerInfo()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.