gpt4 book ai didi

java - HttpSessionListener.sessionCreated() 未被调用

转载 作者:行者123 更新时间:2023-11-29 04:36:46 25 4
gpt4 key购买 nike

我有一个非常简单的 Servlet 和一个非常简单的 HttpSessionListener:

@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;


@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
getServletContext().setAttribute("applicationHits", new AtomicInteger(0));
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("get");

((AtomicInteger) request.getServletContext().getAttribute("applicationHits")).incrementAndGet();
((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
request.setAttribute("requestHits", 0);

getServletContext().getRequestDispatcher("/view/HelloWorld.jsp").forward(request, response);
}

}

@WebListener
public class SessionListener implements HttpSessionListener {

public SessionListener() {
}

public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("session listener");
arg0.getSession().setAttribute("sessionHits", new AtomicInteger(0));
}

public void sessionDestroyed(HttpSessionEvent arg0) {
}

}

我的 HttpSessionListener.sessionCreated() 方法从未被调用(没有日志输出),我最终在调用 getSession( )

((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
request.setAttribute("requestHits", 0);

我也尝试在没有 true 的情况下调用 getSession(),但同样的问题。

我不明白 - @WebListener 注释是否足以调用我的监听器? Eclipse 甚至在 Deployment Descriptor/Listeners 下将其显示为监听器。

最佳答案

如果您不使用@WebListener,请确保在 web.xml 中引用了您的监听器。

<web-app>...
<listener>
<listener-class>com.yoursite.YourSessionListener</listener-class>
</listener>

In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext.

关于java - HttpSessionListener.sessionCreated() 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082885/

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