1、Tomcat中相关对象的生命周期
(1)ServletContext:应用程序生命周期内,被所有Request和Session共享
(2)Servlet、Filter、Listener:应用程序生命周期内,被所有Request和Session共享
(3)HttpSession:客户端(浏览器)不关闭(同一实例),并且在Server中没有过期,被所有持有相同Session的Request共享
(4)HttpServletRequest、HttpServletResponse:一次请求到响应输出完毕,不共享
2、Servlet和Filter非线程安全
不能将Request或Session级别的数据赋值给Servlet或Filter的实例变量
public class ExampleServlet extends HttpServlet {
private Object thisIsNOTThreadSafe;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadSafe;
thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
}
}
本文介绍了Tomcat环境中各类对象的生命周期,包括ServletContext、Servlet、Filter等,并重点强调了Servlet和Filter的非线程安全性特点,以及如何正确处理线程安全问题。
4896

被折叠的 条评论
为什么被折叠?



