This section contains detailed description of @WebInitParam annotation and its implementation with sample code.
The @WebInitParam is used to set parameters which is available trough out in the context of a Servlet or filter in a web application. Only Servlet or Filter for which these init parameters are set ,can access the init parameters.
Prior to Servlet 3.0, the <init-param> can be set in web.xml as follows :
<servlet> <servlet-name>roseindiaServlet</servlet-name> <servlet-class>net.roseindia.RoseindiaServlet</servlet-class> <init-param> <param-name>myParam</param-name> <param-value>paramValue</param-value> </init-param> </servlet>
Now (in Servlet 3.0), you can set the init parameter using annotation @WebInitParam as follows :
@WebServlet(value="/user",
initParams = {
@WebInitParam(name="rose", value="Hello "),
@WebInitParam(name="india", value=" World!")
})
The @WebInitParam has the following attributes :
The tools and technology used in the example is given below :
In the below tutorial, you will learn to set the init parameters using @WebInitParam , which we also read and displays as output :
package roseindia;
import java.io.IOException;
import java.io.PrintWriter;
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(asyncSupported = false, name = "WebInitParamAnnotation", urlPatterns = { "/initparamServlet" }, initParams = {
@WebInitParam(name = "param1", value = "Rose"),
@WebInitParam(name = "param2", value = "India") })
public class WebInitParamAnnotation extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Writing response to display on page
out.write("<html><head><title>@WebInitParam Annotation</title></head>");
out.write("<body>");
out.write("<h2>@WebInitParam Annotation Example</h2>");
out.write("<h3>WELCOME TO <font color='RED'>ROSEINDIA </font>!!!!</h3>");
out.write("<p>The name & value of two init parameter are given below --></p>");
out.write("<p><b>param1</b> --> " + getServletConfig().getInitParameter("param1")+"</p>");
out.write("<p><b>param1</b> --> " + getServletConfig().getInitParameter("param2")+"</p>");
out.write("</body>");
out.write("</html>");
}
}
When you execute the above code, you will get the following output :

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: @WebInitParam
Post your Comment