Reputation: 189
If we are coding a JSP file, we just need to use the embedded "application" object. But how to use it in a Servlet?
Upvotes: 5
Views: 13721
Reputation: 1950
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.
Upvotes: 6
Reputation: 4284
In a Java web application you often have the request
object. So you can get the "application"
object like this:
request.getServletContext().getServerInfo()
Upvotes: 0
Reputation: 1370
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.
Upvotes: 4
Reputation: 115392
Try this:
ServletContext application = getServletConfig().getServletContext();
Upvotes: 3