gpt4 book ai didi

java - 实现 HttpSessionListener

转载 作者:行者123 更新时间:2023-12-01 23:40:37 24 4
gpt4 key购买 nike

我面临着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
}

最佳答案

这种做法是完全错误的。你应该从另一边做。创建一个实现 HttpSessionBindingListenerPlayer 对象并使用它来代替。

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);

当 session 过期或删除属性时,valueUnbound() 将被触发。

<小时/>

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

关于java - 实现 HttpSessionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com