Adding Parameter to Servlet context

Adding Parameter to Servlet context


Posted in : Servlet Posted on : November 9, 2010 at 4:34 PM Comments : [ 0 ]

This section contains the detail about adding Parameter to Servlet context

Adding Parameter to Servlet context

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

Example

In the given below code, the SetContext servlet obtains the ServletConext object in the init() method. In the service() method, the servlet uses the setAttribute() method to set the value of the URL attribute to jdbc:odbc:EmployeesDB. Finally, the servlet uses the PrintWriter object to display the message that the attribute has been set.

package devmanuals;

import javax.servlet.*;
import java.io.*;

public class SetContext extends GenericServlet {
	ServletContext ctx;

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

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		// Set the context attribute
		ctx.setAttribute("URL", "jdbc:odbc:EmployeesDB");
		// Obtain the PrintWriter object */
		PrintWriter pw = response.getWriter();
		// Send response to indicate that the URL attribute has been set
		response.setContentType("text/html");
		pw.println("The JDBC URL has been set as a context attribute");
	}
}

Output :

After compiling the code, When you access the SetContext servlet, it will display the following message in browser :

 Download Source Code 

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics