How to use application object in servlet?

If we are encoding a JSP file, we just need to use the built-in "application" object. But how to use it in a servlet?

+4
source share
4 answers

The application object in the JSP is called the ServletContext object in the servlet. This is available by the inherited method GenericServlet#getServletContext() . You can call this anywhere in your servlet except the init(ServletConfig) method init(ServletConfig) .

 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 .

+5
source

javax.servlet.ServletContext object reference application , and you should be able to reference this 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 now on, you will use the sc object just as you would use the application object in your JSPs.

+4
source

Try the following:

 ServletContext application = getServletConfig().getServletContext(); 
+3
source

In a Java web application, you often have a request object. Thus, you can get the "application" object as follows:

 request.getServletContext().getServerInfo() 
0
source

All Articles