原文链接:http://www.yiidian.com/servlet/servlet-how-work.html
接下来我们有必要了解下Servlet的工作原理,这样才能更好地理解Servlet。本文我们将以之前开发过的Servlet程序来讲解Servlet的内部细节。
1 Servlet基本执行过程
Web容器(如Tomcat)判断当前请求是否第一次请求Servlet程序 。
如果是第一次,则Web容器执行以下任务:
加载Servlet类。
实例化Servlet类。
调用init方法并传入ServletConfig对象
如果不第一次执行,则:
调用service方法,并传入request和response对象
Web容器在需要删除Servlet时(例如,在停止服务器或重新部署项目时)将调用destroy方法。
2 Web容器如何处理Servlet请求
Web容器负责处理请求。让我们看看它如何处理请求。
3 public的service方法部分源码
public的service方法将ServletRequest对象转换为HttpServletRequest类型,而ServletResponse对象转换为HttpServletResponse类型。然后,调用传递这些对象的服务方法。让我们看一下内部代码:
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest)req; response = (HttpServletResponse)res; } catch(ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
4 protected的service方法部分源码
protected的service方法判断请求的类型,如果请求类型为GET,则调用doGet方法,如果请求类型为POST,则调用doPost方法,依此类推。让我们看一下内部代码:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if(method.equals("GET")) { long lastModified = getLastModified(req); if(lastModified == -1L) { doGet(req, resp); } .... //rest of the code } }
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4