2

我面临着类似的问题,并且了解到我的侦听器类将在读取 web.xml 时被实例化。我在侦听器类中有几个函数被主 servlet 的 doPost(它与数据库(mysql)交互以读取/写入有关用户的数据。)以及 HttpSessionListener 的方法。那么是什么阻止了容器加载侦听器类。我收到 404 错误。

片段:

public class EntryServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {


    PlayersList playa = new PlayersList(); //listener class

    if(!playa.isExisting(params[3])){
        if(params[1].equals("Register")){           
            playa.addPlayer(params);
        }
    }       
    else
        out.println("Username already exists");


    if(playa.isExisting(params[argUName],params[argUPwd])){
        HttpSession session = request.getSession(true);     
        session.setMaxInactiveInterval(600);            
        HashMap playersMap = playa.getActivePlayers();
        //code . .
    }
    else
        out.println("Couldn't locate player Name!");    
        out.println(playa.getIn());         
}

监听类:

public class PlayersList implements HttpSessionListener{
private Connection cn;
private Statement st;

PlayersList(){
    try{
        Class.forName("com.mysql.jdbc.Driver");
        cn =  DriverManager.getConnection("jdbc:mysql://localhost/homeDbse\'","root","");
        st = cn.createStatement();
    }
    catch(ClassNotFoundException ce){}
    catch(SQLException se){}
    catch(Exception e){}
}   

public boolean isExisting(String player){
    //interaction with dbse
}   

public void addPlayer(String[] args){
    //interaction with dbse

}   
public void sessionCreated(HttpSessionEvent se){
    //session managing
}   
public void sessionDestroyed(HttpSessionEvent se){
    //session managing
}
4

1 回答 1

7

这种做法是完全错误的。你应该从另一边开始。创建一个Player实现HttpSessionBindingListener并使用它的对象。

public class Player implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        // Add player to list.
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        // Remove player from list.
    }

    // ...

}

valueBound()你这样做时将被触发

Player player = new Player(name);
request.getSession().setAttribute("player", player);

valueUnbound()在会话过期或删除属性时触发。


与具体问题无关,您的代码中有严重的 JDBC 问题。每当数据库因为打开时间过长而超时连接时,此应用程序就会崩溃。您应该在尽可能短的范围内打开和关闭连接、语句和结果集。即,在执行 SQL 查询的finally同一块的块中关闭它们。try

于 2011-03-10T13:20:21.640 回答