When creating a servlet we can use the @WebInitParam
to define some init parameters in the servlet configuration section (@WebServlet
). This init parameter can be used to define where a configuration file of our application is stored, define upload path, etc. This simple servlet below shows how to obtain these init parameters value.
package org.kodejava.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(
name = "InitParameterServlet",
urlPatterns = "/init-param",
initParams = {
@WebInitParam(name = "configPath", value = "F:/app/config"),
@WebInitParam(name = "uploadPath", value = "F:/app/uploads")
}
)
public class InitParameterServlet extends HttpServlet
implements javax.servlet.Servlet {
@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 {
// Get application configuration path
String configPath = getInitParameter("configPath");
String uploadPath = getInitParameter("uploadPath");
System.out.println("configPath = " + configPath);
System.out.println("uploadPath = " + uploadPath);
}
}
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