How to pass parameters to a servlet – ServletConfig

Here’s a serlvet code example to demonstrate how to pass a parameter to a servlet by using ServletConfig “init-param” in web.xml

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure inside the “servlet” element


        <servlet>
		<servlet-name>ServletName</servlet-name>
		<servlet-class>com.mkyong.ServletDemo</servlet-class>
		
		<init-param>
			<param-name>email</param-name>
			<param-value>admin@email.com</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>ServletName</servlet-name>
		<url-pattern>/Demo</url-pattern>
	</servlet-mapping>

Servlet code


public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
		PrintWriter pw = response.getWriter();
		pw.println(getServletConfig().getInitParameter("email"));
		
	}

The “getServletConfig().getInitParameter(“email”)” method is use to get the ServletConfig parameter value in web.xml. Btw, this parameter only available for this servlet only. If you want a parameter which allow globally access by whole web application, you need put the parameter in servlet context element.

Here’s an example to pass parameter to whole web application.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
AshishViswanathDifferent between ServleConfig and ServletContextHow to pass parameters to whole web application – ServletContext | Servlet Recent comment authors
newest oldest most voted
Ashish
Guest
Ashish

how to change value of servlet config parameter at runtime.

Viswanath
Guest
Viswanath

Is it possible to extend the above servlet and then to access the init-parameter in the extended servlet.
Like we could create a global variable and save the servletConfig object then to access the variable in the extended servlet.

trackback
Different between ServleConfig and ServletContext

[…] See the ServletContext example here Tags : servleconfig servlet servletcontext mkyong Founder and Chief Editor of […]

trackback
How to pass parameters to whole web application – ServletContext | Servlet

[…] Here’s a example to pass parameter to a servlet only […]