Share on Google+Share on Google+

The getServletContext() method and its uses with example

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 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);



<[email protected] 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". 


Posted on: March 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.