java 如何在 Servlet 中使用“应用程序”对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/765581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:40:43  来源:igfitidea点击:

How to use the "application" object in a Servlet?

javajspservlets

提问by fwoncn

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 文件,我们只需要使用嵌入的“应用程序”对象。但是如何在 Servlet 中使用它呢?

回答by Boiler Bill

The applicationobject in JSP is called the ServletContextobject 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.

applicationJSP中的对象被称为ServletContext在servlet对象。这可以通过继承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(); 
         // ...
    } 

}

See also Different ways to get Servlet Context.

另请参阅获取 Servlet 上下文的不同方法

回答by scheibk

The applicationobject references javax.servlet.ServletContextand 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.

从那时起,您将像在 JSP 中使用应用程序对象一样使用 sc 对象。

回答by John Topley

Try this:

试试这个:

ServletContext application = getServletConfig().getServletContext();

回答by basZero

In a Java web application you often have the requestobject. So you can get the "application"object like this:

在 Java Web 应用程序中,您通常拥有request对象。所以你可以得到这样的"application"对象:

request.getServletContext().getServerInfo()