Java Tutorial/Servlet/ServletContext
Deployment Descriptor
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WebAppProperties extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
ServletContext context = getServletContext();
String displayName = context.getServletContextName();
if (displayName == null) {
displayName = "(no display-name element defined)";
}
out.println("<html>");
out.println("<head>");
out.println("<title>Web Application Properties");
out.println("</title>");
out.println("</head><body>");
out.println("<h1>Web Application Properties</h2>");
out.println("<br>Name: " + displayName);
out.println("<br>Context: " + req.getContextPath());
out.println("<h2><center>");
out.println("Initialization Parameters</center></h2>");
out.println("<br>");
out.println("<center><table border width=80%>");
Enumeration e = context.getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
out.println("<tr>");
out.println("<td>" + name + "</td>");
out.println("<td>" + context.getInitParameter(name) + "</td>");
out.println("</tr>");
}
out.println("</table></center>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}
Get Servlet Context InitParameter
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
private String dbName="";
private String dbPassword="";
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = getServletContext();
dbName = context.getInitParameter("name");
dbPassword = context.getInitParameter("password");
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException
{
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
out.println("<html><head><title>Basic Servlet</title></head>");
out.println("<body>Database username is <b>" + dbName);
out.println("</b><br>Database password is <b>" + dbPassword + "</b>");
out.println("</body></html>");
}
}