java servlet是多线程,servlet的每个实例与servlet中的每个servlet线程之间的区别?

当Servlet容器启动时,它:

读取web.xml;

在类路径中查找声明的Servlet; 和

加载并实例化每个Servlet 只一次。

粗略地,像这样:

String urlPattern = parseWebXmlAndRetrieveServletUrlPattern();

String servletClass = parseWebXmlAndRetrieveServletClass();

HttpServlet servlet = (HttpServlet) Class.forName(servletClass).newInstance();

servlet.init();

servlets.put(urlPattern, servlet); // Similar to a map interface.

这些Servlet存储在内存中,并在每次请求URL与Servlet相关联时重用url-pattern。然后servlet容器执行类似于以下的代码:

for (Entry entry : servlets.entrySet()) {

String urlPattern = entry.getKey();

HttpServlet servlet = entry.getValue();

if (request.getRequestURL().matches(urlPattern)) {

servlet.service(request, response);

break;

}

}

将GenericServlet#service()其反过来决定哪些的doGet(),doPost()等等。要调用基于HttpServletRequest#getMethod()。

您看,servletcontainer 为每个请求重用相同的servlet实例。换句话说:servlet在每个请求之间共享。这就是为什么以线程安全的方式编写servlet代码非常重要 - 这实际上很简单:只是不将请求或会话范围数据分配为servlet实例变量,而只是作为方法局部变量。例如

public class MyServlet 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.

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值