Passing a list from Servlet to Jsp giving null pointer exception

前端 未结 1 1792
北荒
北荒 2021-01-26 13:10

i am trying to print a list of questions(questionList). When the form loads the elements of the list should be printed as labels.

In my java file i am returning a list o

相关标签:
1条回答
  • 2021-01-26 14:08

    That can only happen if you are not invoking the servlet by its URL. Based on the comments you seem to be actually invoking the JSP directly by its URL and you seem not to be understanding servlet mappings.

    Well, in order to get a servlet to preprocess a HTTP request before displaying the results in a JSP, you need to map the servlet on an URL pattern in web.xml and hide the JSP away in /WEB-INF folder so that it can never be called directly, also not by accident, and thus you can always ensure that the JSP can only displayed by invoking the servlet.

    For example, this in web.xml:

    <servlet>
        <servlet-name>home</servlet-name>
        <servlet-class>com.example.controller.HomeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>home</servlet-name>
        <url-pattern>/home</url-pattern>
    </servlet-mapping>
    

    Please note the <url-pattern> of /home. This takes care that the servlet can be invoked by http://localhost:8080/contextname/home where "/contextname" is actually your webapp's context name. When you enter that URL in the browser address bar or click on a link/bookmark pointing to that URL, the servlet's doGet() method will be called. You only need to change those RequestDispatcher lines

    RequestDispatcher rd = getServletContext().getRequestDispatcher("/Home.Index.jsp");
    if (rd != null){    
    rd.forward(request, response);
    

    to the following simpler and more canonical form

    request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request, response);
    

    You also need to move the JSP file to /WEB-INF folder on exactly that path. I've for the sake of clarity renamed the JSP file name. Home.Index.jsp is a rather strange name. You can always rename it back if you want, as long as it's inside the /WEB-INF folder.

    See also:

    • Our Servlets wiki page - Explains how servlets work and contains concrete Hello World examples
    0 讨论(0)
提交回复
热议问题