Saveendra Ekanayake Saveendra Ekanayake - 1 month ago 7
Java Question

Difference between request.getServletContext() and getServletContext()

I have

SampleServlet
class, within that I have override the
doGet()
method as follows

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");

String userid = (String)request.getServletContext().getInitParameter("userid");

out.print("Name = " + name + "<br>");

out.print("User id= " + userid+ "<br>");
}


Within my
Web.xml
i have added context parameters as follows,

<context-param>
<param-name>userid</param-name>
<param-value>ABC12345</param-value>
</context-param>


I used
request.getServletContext().getInitParameter("userid");
statement to access that parameter.
request.getServletContext().getInitParameter("userid");
Its work fine. However is there any difference between
getServletContext().getInitParameter("userid");
and
request.getServletContext().getInitParameter("userid");
Both give me same output but I don't have proper idea about these two.

Answer

getServletContext() you can call directly is only when your code is in a class that extends HttpServlet. That is because HttpServlet base class has this method defined.

ServletContext returned by request.getSession().getServletContext()is same as getServletContext().HttpSessioncontains a reference to the ServletContext that this session belongs to.

As long as your code is in the servlet class, you can use anything as both can be called.

If you have a custom class that doesn't extend servlet and you need to pass the session object to work on it in that custom class.As you have a reference to the session, you can get access to the ServletContext using the method session.getServletContext().