package org.kodejava.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/context-init-param")
public class ContextInitParameter extends HttpServlet implements Servlet {
public ContextInitParameter() {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Get an instance of ServletContext
ServletContext context = getServletContext();
// To read context initialization parameter we can call context.getInitParameter()
// and pass the name of initialization parameter to be read. If the named
// parameter does not exist the returned value will be null.
//
// In this example we read an initialization parameter called LOG.PATH
String logPath = context.getInitParameter("LOG.PATH");
writer.println("Log Path: " + logPath + "<br/>");
// Reads all the name of servlet's initialization parameters. If the
// servlet doesn't have any an empty enumeration will be returned.
Enumeration<String> enumeration = context.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String paramName = enumeration.nextElement();
String paramValue = context.getInitParameter(paramName);
writer.println("Context Init Param: [" + paramName + " = " + paramValue +
"]<br/>");
}
}
}
The context initialization parameter (context-param
) look something like this in the web.xml
file:
<web-app>
...
<context-param>
<param-name>locale</param-name>
<param-value>id_ID</param-value>
</context-param>
<context-param>
<param-name>LOG.PATH</param-name>
<param-value>F:/Logs</param-value>
</context-param>
...
</web-app>
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024