Understanding ServletConfig - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Understanding ServletConfig

Share This

Sometimes it is necessary to provide initial configuration information for Servlets. Configuration information for a Servlet may consist of a string or a set of string values included in the Servlet's web.xml declaration. 


This functionality allows a Servlet to have initial parameters specified outside of the compiled code and changed without needing to recompile the Servlet. Each servlet has an object associated with it called the ServletConfig. This object is created by the container and implements the javax.servlet.ServletConfig interface. It is the ServletConfig that contains the initialization parameters. A reference to this object can be retrieved by calling the getServletConfig() method.


Servlet containers use ServletConfig objects to pass initialization and context information to servlets. The initialization information generally consists of a series of initialization parameters (init parameters) and a ServletContext object, which provides information about the server environment. A servlet can implement ServletConfig to allow easy access to init parameters and context information, as GenericServlet does.


Source Code of TestServ.java
package com.t4b.web.test; 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(value = "/TestServ", initParams = { @WebInitParam(name = "email", value = "email@domain.com", description = "Email from webmaster"), @WebInitParam(name = "phone", value = "xxxx/xx.xx.xx", description = "Phone webmaster") }, description = "Servlet 3 initialisation parameter annotation example: @WebInitParam") public class TestServ extends HttpServlet { private static final long serialVersionUID = 1L; private String email, phone; @Override public void init(ServletConfig config) throws ServletException { email = config.getInitParameter("email"); phone = config.getInitParameter("phone"); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.write("<h2>Servlet 3 initialisation parameter annotation example: @WebInitParam</h2>"); out.write("<p><strong>E-mail: </strong>" + email + "</p>"); out.write("<p><strong>Phone: </strong>" + phone + "</p>"); } public TestServ() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

Happy Exploring!

No comments:

Post a Comment