Declare Servlet 3.0 Initialization parameter using @WebInitParam
- Thursday, November 8, 2012, 19:22
- Java EE
- 29,006 views
Servlet initialization parameters are used to process the data when servlet initializing. Before servlet 3, this data need to put on deployment descriptor and servlet will read the data in init() method using ServletConfig Object. For every servlet, the data is unique and not been shared in between of two servlets.
Before Servlet 3 Initialization parameter declared in web.xml as following
1 2 3 4 5 6 7 8 |
<servlet> <servlet-name>myserlvet</servlet-name> <servlet-class>com.demo.MyServlet</servlet-class> <init-param> <param-name>email</param-name> <param-value>tousifxxxx@xxx.com</param-value> </init-param> </servlet> |
Servlet 3 come with @WebInitParam
annotation, using which developer can define the initialization parameter in Servlet itself. Later servlet can access that parameter by using config.getInitParameter()
method.
1 2 3 4 5 6 7 |
@WebServlet( urlPatterns = {"/initparam"}, initParams = { @WebInitParam (name = "email", value = "tousifxxx@xxx.com"), @WebInitParam (name = "phone", value = "92709xxxxx") } ) |
Following example demonstrate the use of @WebInitParam annotation in Servlet 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package org.techzoo.servlet3; 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( urlPatterns = {"/initparam"}, initParams = { @WebInitParam (name = "email", value = "tousifxxx@xxx.com"), @WebInitParam (name = "phone", value = "92709xxxxx") } ) public class ServletInitParamDemo extends HttpServlet { private static final long serialVersionUID = 1L; private String email = "", phone = ""; public ServletInitParamDemo() { super(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); email = config.getInitParameter("email"); phone = config.getInitParameter("phone"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String html = "<h2>Access data using @WebInitParam</h2>"; PrintWriter out = response.getWriter(); html +="<h3>Email : "+email+"<br/>Phone No. : "+phone+"</h3>"; out.println(html); } } |
The output will look like similar to following…