简体   繁体   中英

Why instantiating my class doesn't work with getServletContext()?

I would like to create a controller for my jsp page and I am wondering why should I use this.getServletContext() rather than creating an instance of my class. Let's say HelloWorld world = new HelloWorld(); then world.getServletContext() etc.

here's my code:

public class HelloWorld extends HttpServlet {

    /**
     *
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException {
        HelloWorld world = new HelloWorld();
        world.getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);

    }

I get this:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

I am wondering why should I use this.getServletContext() rather than creating an instance of my class lets say HelloWorld world = new HelloWorld(); then world.getServletContext() ...etc ?

The reason is that Servlets are not designed to work the way you mentioned. Here is the definition of a Servlet in Servlet Specification :

A servlet is a Java technology-based Web component, managed by a container , that generates dynamic content.

The term managed by a container means the servlet container is responsible to execute the lifecycle (creating, initializing, handling requests and destroying) of the servlet. But if you use new to create the servlet you are trying to work against the specification, and it will not work.

Read the section 2.3 Servlet Life Cycle of the specification and it will answer your question thoroughly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM