If we are coding a JSP file, we just need to use the embedded "application" object. But how to use it in a Servlet?
Asked
Active
Viewed 1.4k times
4 Answers
6
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.

Community
- 1
- 1

Boiler Bill
- 1,900
- 1
- 22
- 32
4
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.

scheibk
- 1,370
- 3
- 10
- 19
3
Try this:
ServletContext application = getServletConfig().getServletContext();

John Topley
- 113,588
- 46
- 195
- 237
0
In a Java web application you often have the request
object. So you can get the "application"
object like this:
request.getServletContext().getServerInfo()

basZero
- 4,129
- 9
- 51
- 89