Saveendra Ekanayake Saveendra Ekanayake - 1 year ago 158
Java Question

Difference between request.getServletContext() and getServletContext()

I have

class, within that I have override the
method as follows

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

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
i have added context parameters as follows,


I used
statement to access that parameter.
Its work fine. However is there any difference between
Both give me same output but I don't have proper idea about these two.

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download