Context Params How to get context parameters in servlets Retrieving context params in servlets

Context Parameters

We can provide the context parameters for an application,insdie the web.xml file.These parameters are specific to a particular application and are initialised at the time application is loaded. Inside the web.xml file we declare a particular context param as shown below in the web.xml fragment :















Here inside the web-app tag where we define the servlet-name and servletclass tags,we introduce the context-param tags which consist of param-name and param-value tags.param-name is the name of the context parameter and param-value is the value to which it has to be initialised.

Inside the servlet code we can access the context parameters from the servlet context object.Servlet context instance can be get from the inherited getServletContext() method.

The servlet code below illustrates the above :



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


PrintWriter out = response.getWriter();



out.println(“<title>Servlet HelloWorld</title>”);



out.println(“<h1>Context Parameter username is ” + getServletContext().getInitParameter(“username”) + “</h1>”);





Here we get the context parameter “username” declared in the web.xml file by calling the method getInitParameter(“username”) on the servlet context object.The getInitParameter() method takes the name of the context parameter as string.The method getInitParameterNames() returns the enumeration of parameter values,all of which are declared in the web.xml file.Having run the above servlet code we get the output as :

Context Parameter username is Steve

steve is the value with which we inialised the context parameter,username in the web.xml file.

Number of View :3136


  1. #1 written by Garretot October 18th, 2010 at 14:16

    Hola, – da mejor. Guardar va!


    RE Q

Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache