Home Tutorial Java Servlet The getServletContext() method and its uses with example


Share on Google+Share on Google+
The getServletContext() method and its uses with example
Posted on: March 23, 2010 at 12:00 AM
In this tutorial you will see that how getServletContext() method is used in servlet.


ServletContext is an interface found in javax.servlet package. It define few methods that is used by servlet to communicate with its servlet container like dispatch request or write the log file.

The ServletConfig object hold the ServletContext object which is provided by the web server when the servlet is initialized.

The method getServletContext returns the ServletContext to which session it belongs.

Code Sample:


package package1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

getServletContext().setAttribute("attribute", "attributeValue");

RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


At the browser will see the value of the attribute ie. "attributeValue". 


Related Tags for The getServletContext() method and its uses with example:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 23, 2010

Recommend the tutorial

Advertisements Advertisements