Getting Parameter from Servlet Context

Posted in : Servlet Posted on : November 9, 2010 at 4:45 PM Comments : [ 0 ]
This section contains the details about Getting Parameter from Servlet Context.

Getting Parameter from Servlet Context

In this section, you will learn how to get a JDBC URL as a context attribute using getAttribute() method.


In the given below code, the RetrievingCntx servlet obtains the ServletConext object in the init() method. In the service() method, the servlet uses the getAttribute() method to obtain the value of the URL attribute. Finally, the servlet uses the PrintWriter object to display the value of the attribute.

The GetCntx servlet retrieves the URL attribute and displays the value of the attribute. You can use the following code to create the servlet, GetCntx to retrieve and display the URL attribute :

package devmanuals;

import javax.servlet.*;

public class GetCntx extends GenericServlet {
	ServletContext ctx;
	String url;

	public void init(ServletConfig cfig) {
		// Obtain the ServletContext object
		ctx = cfig.getServletContext();

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		// Retrieve the URL attribute
		url = (String) ctx.getAttribute("URL");
		// Obtain a PrintWriter object
		PrintWriter pw = response.getWriter();
		// Send response to display the value of the URL attribute
		pw.println("The URL value is : " + url + "
"); } }

Output :

When you access the GetCntx servlet, it retrieves the URL that was set by the SetContext servlet in the previous example. The servlet sends a response to display the value of the URL, as shown in the following figure:

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Tutorial Topics