The following example code demonstrates How to Display Context Parameters Using Servlets.
Here is an example of a servlet that creates and displays context parameters.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = getServletContext();
context.setAttribute("database", "Oracle");
context.setAttribute("server", "Apache Tomcat");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Context Information</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Context Information</h1>");
out.println("<p>Database: " + context.getAttribute("database") + "</p>");
out.println("<p>Server: " + context.getAttribute("server") + "</p>");
out.println("</body>");
out.println("</html>");
}
}
In this example, the ContextInfoServlet
class handles GET requests. The servlet creates two context parameters, database
and server
, using the setAttribute
method of the ServletContext
object. The values of the context parameters are retrieved using the getAttribute
method and displayed in an HTML page.