Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jsp

servlets

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

like image 780
fwoncn Avatar asked Apr 19 '09 15:04

fwoncn


2 Answers

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.

like image 192
Boiler Bill Avatar answered Nov 04 '22 23:11

Boiler Bill


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.

like image 41
scheibk Avatar answered Nov 04 '22 23:11

scheibk