ServletContextListener中的ArrayLists

时间:2014-05-10 19:51:18

标签: java jsp arraylist

我是Jsp的新手,并开始使用Servlets和Listeners进行一些测试。 我的问题是,当我启动ListenTest.do时,为什么我会收到HTTP状态404 - /DynamicExample/ListenTest.do?

我想要做的是声明多个狗对象并将其放在ArrayList中。当所有对象都存储到ArrayList中时,“MyServletContextListener.java”将设置属性“dog”。完成后,我会将该属性发送到我的index.jsp页面,但是得到的是404文件而不是fount。

ListenTester.java

package com.app.control;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.app.model.Dog;

public class ListenerTester extends HttpServlet {

    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Dog dog = (Dog) getServletContext().getAttribute("dog");
        RequestDispatcher forwardToLoginPage = req.getRequestDispatcher("index.jsp");
        forwardToLoginPage.forward(req, resp);
    }
}

MyServletContextListener.java

package com.app.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.app.model.Dog;

public class MyServletContextListener implements ServletContextListener {

    ArrayList<Dog> allDogs;

    public void contextInitialized(ServletContextEvent event) { 
        if (allDogs == null) { allDogs = new ArrayList<Dog>(); } 
        allDogs = (ArrayList<Dog>) event.getServletContext().getAttribute("dog");

        Dog d1 = new Dog("SomeThing");
        Dog d2 = new Dog("someThing");
        allDogs.add(d1);
        allDogs.add(d2);
        event.getServletContext().setAttribute("dog", allDogs);
    }

    public void contextDestroyed(ServletContextEvent event) { 
         // nothing to do here
    }
}

1 个答案:

答案 0 :(得分:2)

ArrayList<Dog>无法投放到Dog


您正在ServletContext进行设置,如下所示

allDogs = new ArrayList<Dog>();
...
event.getServletContext().setAttribute("dog", allDogs);

现在您正在检索它,如下所示

Dog dog = (Dog) getServletContext().getAttribute("dog");//the problem is here

应该是

ArrayList<Dog> dogs = (ArrayList<Dog>) getServletContext().getAttribute("dog");

以这种方式避免NullPointerException

public void contextInitialized(ServletContextEvent event) { 
    //if (allDogs == null) { allDogs = new ArrayList<Dog>(); } //move this line below
    allDogs = (ArrayList<Dog>) event.getServletContext().getAttribute("dog");
    if (allDogs == null) { allDogs = new ArrayList<Dog>(); } 
    ...
}

无需在请求中设置“dog”属性,因为它已添加为会话属性。

index.jsp的示例代码:

<%@ page import="java.util.ArrayList,com.x.y.z.Dog" %>
<%
    ArrayList<Dog> dogs = (ArrayList<Dog>) session.getAttribute("dog"); 
    for(Dog dog:dogs){
        out.println(dog.getName());
    }
%> 

注意:使用JavaServer Pages Standard Tag Library代替Scriplets