简体   繁体   中英

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. But how to use it in a Servlet?

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(); 
         // ...
    } 

}

See also Different ways to get Servlet Context .

The application object references javax.servlet.ServletContext and you should be able to reference that in your servlets.

To reference the ServletContext you will need to do the following:

// 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.

尝试这个:

ServletContext application = getServletConfig().getServletContext();

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

request.getServletContext().getServerInfo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM