如何使用“应用程序” Servlet中的对象? [英] How to use the "application" object in a Servlet?

查看:144
本文介绍了如何使用“应用程序” Servlet中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们编写JSP文件,我们只需要使用嵌入的应用程序对象。但是如何在Servlet中使用它?

If we are coding a JSP file, we just need to use the embedded "application" object. But how to use it in a Servlet?

推荐答案

应用程序对象在JSP中称为 ServletContext servlet中的对象。这可以通过继承的 <$ c $获得。 c> GenericServlet#getServletContext() 方法。你可以在servlet中的任何地方调用它,除了 init(ServletConfig)方法。

The application object in JSP is called the ServletContext object in a servlet. This is available by the inherited GenericServlet#getServletContext() method. You can call this anywhere in your servlet except of the 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上下文的不同方法

这篇关于如何使用“应用程序” Servlet中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆