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
Advertisement
In this tutorial you will see that how getServletContext() method is used in servlet.

Description:

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:

FirstServlet.java  

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 {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

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

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

}
}

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsp</title>
</head>
<body>
<%
out.print(getServletContext().getAttribute("attribute"));
%>
</body>
</html>
 

Output:

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

Advertisement

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
 

 

 

DMCA.com