我正面临一个similar problem并且已经知道我的侦听器类将在读取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
}
答案 0 :(得分:6)
这种做法完全错误。你应该从另一边做。创建一个实现HttpSessionBindingListener
的Player
对象并改为使用它。
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
块中。