ServletContext context = getServletContext(); String appName = context.getServletContextName(); System.out.println("Application name: " + appName);
@WebServlet(name = "ExampleServlet", urlPatterns = {"/example"}) public class ExampleServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String appName = context.getServletContextName(); response.getWriter().print("Application name: " + appName); } }This example demonstrates using the getServletContextName method in a servlet. When the servlet is accessed via the "/example" URL pattern, the doGet method is called. The ServletContext is retrieved and the name of the web application is sent in the response. The javax.servlet package library is used for implementing Java Servlets.