Servlets Basics 2 - error in request.getServletContext - "getServletContext() undefined"

702 views
Skip to first unread message

Ravi B

unread,
Jun 7, 2016, 7:42:17 AM6/7/16
to JPassion.com: Java Programming
Hello,
I am doing the homework for servlet_basics2 chapter from the WebProgramming Basics course. I'm trying to declare a variable of ServletContext class type as follows:

        ServletContext servletcontext = request.getServletContext();
        servcontext.setAttribute("Country", "USA");


I am getting an error as follows: The method getServletContext() is undefined for the type HttpServletRequest.

The example program "hello_scope_context" has the exact same declaration and it works fine, but when I declare it, it's giving me this error. Can you help? Thanks. Here is my code:

------------------
package hwservlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class GreetingServlet extends HttpServlet {
    @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/html");
        response.setBufferSize(8192);

        PrintWriter out = response.getWriter();

        // Set Servlet wide scope attribute to be accessible by any servlet
        ServletContext servletcontext = request.getServletContext();
        servcontext.setAttribute("Country", "USA");
-----------------------------

Ravi B

unread,
Jun 7, 2016, 8:46:35 AM6/7/16
to JPassion.com: Java Programming
Please read the last line as servletcontext.setAttribute("Country","USA");
Reply all
Reply to author
Forward
0 new messages