@WebInitParam Annotation
The @WebInitParam annotation is used to provide initialization parameters to any Servlet component. These initialization parameters must be passed to the Servlet or the Filter. The @WebInitParam annotation is an attribute of the @WebServlet and @WebFilter annotation.
We can add @WebServlet annotation in a Servlet class that can contain the metadata about the Servlet that is being created. We can provide the name and value of init-param using the initParams attribute. To provide this initParam attribute values the @WebInitParam annotation is used. However, this information can be added to the web.xml (deployment descriptor) also.
@WebInitParam Annotation Attributes
There are two attributes of the @WebInitParam annotation name and value,
![]() |
@WebInitParam Annotation |
The Name attribute to specify the name of the parameter and the value attribute to specify the value of the initialization parameter. We can access init-params by getInitParameter(String name) method described by the ServletConfig interface.
@WebInitParam Annotation Example
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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;
@WebServlet( //<-
@WebServlet Annotation
//Attributes
initParams = {
@WebInitParam(name = "author_name", value = "Pushpendra")
},
urlPatterns = {
"/AnnotationDemo",
"/WebServletAnnotation"
}
)
public class AnnotationDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
public AnnotationDemo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pout=response.getWriter();
response.setContentType("text/html");
ServletConfig config=getServletConfig();
String author_name=config.getInitParameter("author_name");
String servlet_name=config.getServletName();
pout.append("<html><body><h3>Written
by<br>"+author_name+"</h3><br>"+servlet_name+"</body></html>");
}
}
Result:
![]() |
@WebInitParam annotation example |