The getServletContext() method and its uses with example


 

The getServletContext() method and its uses with example

In this tutorial you will see that how getServletContext() method is used in servlet.

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". 

Ads